home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / xulrunner-1.9.1.5 / components / nsUpdateService.js < prev    next >
Text File  |  2009-11-09  |  103KB  |  3,119 lines

  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /*
  3. //@line 44 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  4. */
  5.  
  6. const Cc = Components.classes;
  7. const Ci = Components.interfaces;
  8. const Cr = Components.results;
  9.  
  10. Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
  11.  
  12. const PREF_APP_UPDATE_ENABLED             = "app.update.enabled";
  13. const PREF_APP_UPDATE_AUTO                = "app.update.auto";
  14. const PREF_APP_UPDATE_MODE                = "app.update.mode";
  15. const PREF_APP_UPDATE_SILENT              = "app.update.silent";
  16. const PREF_APP_UPDATE_INTERVAL            = "app.update.interval";
  17. const PREF_APP_UPDATE_TIMER               = "app.update.timer";
  18. const PREF_APP_UPDATE_IDLETIME            = "app.update.idletime";
  19. const PREF_APP_UPDATE_PROMPTWAITTIME      = "app.update.promptWaitTime";
  20. const PREF_APP_UPDATE_LOG_BRANCH          = "app.update.log.";
  21. const PREF_APP_UPDATE_URL                 = "app.update.url";
  22. const PREF_APP_UPDATE_URL_OVERRIDE        = "app.update.url.override";
  23. const PREF_APP_UPDATE_URL_DETAILS         = "app.update.url.details";
  24. const PREF_APP_UPDATE_CHANNEL             = "app.update.channel";
  25. const PREF_APP_UPDATE_SHOW_INSTALLED_UI   = "app.update.showInstalledUI";
  26. const PREF_APP_UPDATE_LASTUPDATETIME_FMT  = "app.update.lastUpdateTime.%ID%";
  27. const PREF_APP_UPDATE_INCOMPATIBLE_MODE   = "app.update.incompatible.mode";
  28. const PREF_UPDATE_NEVER_BRANCH            = "app.update.never.";
  29. const PREF_PARTNER_BRANCH                 = "app.partner.";
  30. const PREF_APP_DISTRIBUTION               = "distribution.id";
  31. const PREF_APP_DISTRIBUTION_VERSION       = "distribution.version";
  32.  
  33. const URI_UPDATE_PROMPT_DIALOG  = "chrome://mozapps/content/update/updates.xul";
  34. const URI_UPDATE_HISTORY_DIALOG = "chrome://mozapps/content/update/history.xul";
  35. const URI_BRAND_PROPERTIES      = "chrome://branding/locale/brand.properties";
  36. const URI_UPDATES_PROPERTIES    = "chrome://mozapps/locale/update/updates.properties";
  37. const URI_UPDATE_NS             = "http://www.mozilla.org/2005/app-update";
  38.  
  39. const KEY_APPDIR          = "XCurProcD";
  40. const KEY_GRED            = "GreD";
  41. //@line 85 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  42.  
  43. const DIR_UPDATES         = "updates";
  44. const FILE_UPDATE_STATUS  = "update.status";
  45. const FILE_UPDATE_VERSION = "update.version";
  46. const FILE_UPDATE_ARCHIVE = "update.mar";
  47. const FILE_UPDATE_LOG     = "update.log"
  48. const FILE_UPDATES_DB     = "updates.xml";
  49. const FILE_UPDATE_ACTIVE  = "active-update.xml";
  50. const FILE_PERMS_TEST     = "update.test";
  51. const FILE_LAST_LOG       = "last-update.log";
  52. const FILE_UPDATE_LOCALE  = "update.locale";
  53.  
  54. const MODE_RDONLY   = 0x01;
  55. const MODE_WRONLY   = 0x02;
  56. const MODE_CREATE   = 0x08;
  57. const MODE_APPEND   = 0x10;
  58. const MODE_TRUNCATE = 0x20;
  59.  
  60. const PERMS_FILE      = 0644;
  61. const PERMS_DIRECTORY = 0755;
  62.  
  63. const STATE_NONE            = "null";
  64. const STATE_DOWNLOADING     = "downloading";
  65. const STATE_PENDING         = "pending";
  66. const STATE_APPLYING        = "applying";
  67. const STATE_SUCCEEDED       = "succeeded";
  68. const STATE_DOWNLOAD_FAILED = "download-failed";
  69. const STATE_FAILED          = "failed";
  70.  
  71. // From updater/errors.h:
  72. const WRITE_ERROR = 7;
  73.  
  74. const DOWNLOAD_CHUNK_SIZE           = 300000; // bytes
  75. const DOWNLOAD_BACKGROUND_INTERVAL  = 600;    // seconds
  76. const DOWNLOAD_FOREGROUND_INTERVAL  = 0;
  77.  
  78. const UPDATE_WINDOW_NAME      = "Update:Wizard";
  79. const TOOLKIT_ID              = "toolkit@mozilla.org";
  80.  
  81. const POST_UPDATE_CONTRACTID = "@mozilla.org/updates/post-update;1";
  82.  
  83. var gApp        = null;
  84. var gPref       = null;
  85. var gABI        = null;
  86. var gOSVersion  = null;
  87. var gLocale     = null;
  88. var gConsole    = null;
  89. var gCanUpdate  = null;
  90. var gLogEnabled = { };
  91.  
  92. // shared code for suppressing bad cert dialogs
  93. //@line 41 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/shared/src/badCertHandler.js"
  94.  
  95. /**
  96.  * Only allow built-in certs for HTTPS connections.  See bug 340198.
  97.  */
  98. function checkCert(channel) {
  99.   if (!channel.originalURI.schemeIs("https"))  // bypass
  100.     return;
  101.  
  102.   const Ci = Components.interfaces;  
  103.   var cert =
  104.       channel.securityInfo.QueryInterface(Ci.nsISSLStatusProvider).
  105.       SSLStatus.QueryInterface(Ci.nsISSLStatus).serverCert;
  106.  
  107.   var issuer = cert.issuer;
  108.   while (issuer && !cert.equals(issuer)) {
  109.     cert = issuer;
  110.     issuer = cert.issuer;
  111.   }
  112.  
  113.   var errorstring = "cert issuer is not built-in";
  114.   if (!issuer)
  115.     throw errorstring;
  116.  
  117.   issuer = issuer.QueryInterface(Ci.nsIX509Cert3);
  118.   var tokenNames = issuer.getAllTokenNames({});
  119.  
  120.   if (!tokenNames.some(isBuiltinToken))
  121.     throw errorstring;
  122. }
  123.  
  124. function isBuiltinToken(tokenName) {
  125.   return tokenName == "Builtin Object Token";
  126. }
  127.  
  128. /**
  129.  * This class implements nsIBadCertListener.  Its job is to prevent "bad cert"
  130.  * security dialogs from being shown to the user.  It is better to simply fail
  131.  * if the certificate is bad. See bug 304286.
  132.  */
  133. function BadCertHandler() {
  134. }
  135. BadCertHandler.prototype = {
  136.  
  137.   // nsIChannelEventSink
  138.   onChannelRedirect: function(oldChannel, newChannel, flags) {
  139.     // make sure the certificate of the old channel checks out before we follow
  140.     // a redirect from it.  See bug 340198.
  141.     checkCert(oldChannel);
  142.   },
  143.  
  144.   // Suppress any certificate errors
  145.   notifyCertProblem: function(socketInfo, status, targetSite) {
  146.     return true;
  147.   },
  148.  
  149.   // Suppress any ssl errors
  150.   notifySSLError: function(socketInfo, error, targetSite) {
  151.     return true;
  152.   },
  153.  
  154.   // nsIInterfaceRequestor
  155.   getInterface: function(iid) {
  156.     return this.QueryInterface(iid);
  157.   },
  158.  
  159.   // nsISupports
  160.   QueryInterface: function(iid) {
  161.     if (!iid.equals(Components.interfaces.nsIChannelEventSink) &&
  162.         !iid.equals(Components.interfaces.nsIBadCertListener2) &&
  163.         !iid.equals(Components.interfaces.nsISSLErrorListener) &&
  164.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  165.         !iid.equals(Components.interfaces.nsISupports))
  166.       throw Components.results.NS_ERROR_NO_INTERFACE;
  167.     return this;
  168.   }
  169. };
  170. //@line 137 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  171.  
  172. /**
  173.  * Logs a string to the error console.
  174.  * @param   string
  175.  *          The string to write to the error console..
  176.  */
  177. function LOG(module, string) {
  178.   if (module in gLogEnabled || "all" in gLogEnabled) {
  179.     dump("*** AUS:SVC " + module + ":" + string + "\n");
  180.     // On startup gConsole may not be initialized
  181.     if (gConsole)
  182.       gConsole.logStringMessage("AUS:SVC " + module + ":" + string);
  183.   }
  184. }
  185.  
  186. /**
  187.  * Convert a string containing binary values to hex.
  188.  */
  189. function binaryToHex(input) {
  190.   var result = "";
  191.   for (var i = 0; i < input.length; ++i) {
  192.     var hex = input.charCodeAt(i).toString(16);
  193.     if (hex.length == 1)
  194.       hex = "0" + hex;
  195.     result += hex;
  196.   }
  197.   return result;
  198. }
  199.  
  200. /**
  201.  * Gets a File URL spec for a nsIFile
  202.  * @param   file
  203.  *          The file to get a file URL spec to
  204.  * @returns The file URL spec to the file
  205.  */
  206. function getURLSpecFromFile(file) {
  207.   var ioServ = Cc["@mozilla.org/network/io-service;1"].
  208.                getService(Ci.nsIIOService);
  209.   var fph = ioServ.getProtocolHandler("file").
  210.             QueryInterface(Ci.nsIFileProtocolHandler);
  211.   return fph.getURLSpecFromFile(file);
  212. }
  213.  
  214. /**
  215.  * Gets the specified directory at the specified hierarchy under a
  216.  * Directory Service key.
  217.  * @param   key
  218.  *          The Directory Service Key to start from
  219.  * @param   pathArray
  220.  *          An array of path components to locate beneath the directory
  221.  *          specified by |key|
  222.  * @return  nsIFile object for the location specified. If the directory
  223.  *          requested does not exist, it is created, along with any
  224.  *          parent directories that need to be created.
  225.  */
  226. function getDir(key, pathArray) {
  227.   return getDirInternal(key, pathArray, true, false);
  228. }
  229.  
  230. /**
  231.  * Gets the specified directory at the specified hierarchy under a
  232.  * Directory Service key.
  233.  * @param   key
  234.  *          The Directory Service Key to start from
  235.  * @param   pathArray
  236.  *          An array of path components to locate beneath the directory
  237.  *          specified by |key|
  238.  * @return  nsIFile object for the location specified. If the directory
  239.  *          requested does not exist, it is NOT created.
  240.  */
  241. function getDirNoCreate(key, pathArray) {
  242.   return getDirInternal(key, pathArray, false, false);
  243. }
  244.  
  245. /**
  246.  * Gets the specified directory at the specified hierarchy under the
  247.  * update root directory.
  248.  * @param   pathArray
  249.  *          An array of path components to locate beneath the directory
  250.  *          specified by |key|
  251.  * @return  nsIFile object for the location specified. If the directory
  252.  *          requested does not exist, it is created, along with any
  253.  *          parent directories that need to be created.
  254.  */
  255. function getUpdateDir(pathArray) {
  256.   return getDirInternal(KEY_APPDIR, pathArray, true, true);
  257. }
  258.  
  259. /**
  260.  * Gets the specified directory at the specified hierarchy under a
  261.  * Directory Service key.
  262.  * @param   key
  263.  *          The Directory Service Key to start from
  264.  * @param   pathArray
  265.  *          An array of path components to locate beneath the directory
  266.  *          specified by |key|
  267.  * @param   shouldCreate
  268.  *          true if the directory hierarchy specified in |pathArray|
  269.  *          should be created if it does not exist,
  270.  *          false otherwise.
  271.  * @param   update
  272.  *          true if finding the update directory,
  273.  *          false otherwise.
  274.  * @return  nsIFile object for the location specified.
  275.  */
  276. function getDirInternal(key, pathArray, shouldCreate, update) {
  277.   var fileLocator = Cc["@mozilla.org/file/directory_service;1"].
  278.                     getService(Ci.nsIProperties);
  279.   var dir = fileLocator.get(key, Ci.nsIFile);
  280. //@line 254 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  281.   for (var i = 0; i < pathArray.length; ++i) {
  282.     dir.append(pathArray[i]);
  283.     if (shouldCreate && !dir.exists())
  284.       dir.create(Ci.nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  285.   }
  286.   return dir;
  287. }
  288.  
  289. /**
  290.  * Gets the file at the specified hierarchy under a Directory Service key.
  291.  * @param   key
  292.  *          The Directory Service Key to start from
  293.  * @param   pathArray
  294.  *          An array of path components to locate beneath the directory
  295.  *          specified by |key|. The last item in this array must be the
  296.  *          leaf name of a file.
  297.  * @return  nsIFile object for the file specified. The file is NOT created
  298.  *          if it does not exist, however all required directories along
  299.  *          the way are.
  300.  */
  301. function getFile(key, pathArray) {
  302.   var file = getDir(key, pathArray.slice(0, -1));
  303.   file.append(pathArray[pathArray.length - 1]);
  304.   return file;
  305. }
  306.  
  307. /**
  308.  * Gets the file at the specified hierarchy under the update root directory.
  309.  * @param   pathArray
  310.  *          An array of path components to locate beneath the directory
  311.  *          specified by |key|. The last item in this array must be the
  312.  *          leaf name of a file.
  313.  * @return  nsIFile object for the file specified. The file is NOT created
  314.  *          if it does not exist, however all required directories along
  315.  *          the way are.
  316.  */
  317. function getUpdateFile(pathArray) {
  318.   var file = getUpdateDir(pathArray.slice(0, -1));
  319.   file.append(pathArray[pathArray.length - 1]);
  320.   return file;
  321. }
  322.  
  323. /**
  324.  * Closes a Safe Output Stream
  325.  * @param   fos
  326.  *          The Safe Output Stream to close
  327.  */
  328. function closeSafeOutputStream(fos) {
  329.   if (fos instanceof Ci.nsISafeOutputStream) {
  330.     try {
  331.       fos.finish();
  332.     }
  333.     catch (e) {
  334.       fos.close();
  335.     }
  336.   }
  337.   else
  338.     fos.close();
  339. }
  340.  
  341. /**
  342.  * Returns human readable status text from the updates.properties bundle
  343.  * based on an error code
  344.  * @param   code
  345.  *          The error code to look up human readable status text for
  346.  * @param   defaultCode
  347.  *          The default code to look up should human readable status text
  348.  *          not exist for |code|
  349.  * @returns A human readable status text string
  350.  */
  351. function getStatusTextFromCode(code, defaultCode) {
  352.   const updateBundle = Cc["@mozilla.org/intl/stringbundle;1"].
  353.                        getService(Ci.nsIStringBundleService).
  354.                        createBundle(URI_UPDATES_PROPERTIES);
  355.   var reason;
  356.   try {
  357.     reason = updateBundle.GetStringFromName("check_error-" + code);
  358.     LOG("General", "getStatusTextFromCode - transfer error: " + reason +
  359.         ", code: " + code);
  360.   }
  361.   catch (e) {
  362.     // Use the default reason
  363.     reason = updateBundle.GetStringFromName("check_error-" + defaultCode);
  364.     LOG("General", "getStatusTextFromCode - transfer error: " + reason +
  365.         ", default code: " + defaultCode);
  366.   }
  367.   return reason;
  368. }
  369.  
  370. /**
  371.  * Get the Active Updates directory
  372.  * @param   key
  373.  *          The Directory Service Key (optional).
  374.  *          If used, don't search local appdata on Win32 and don't create dir.
  375.  * @returns The active updates directory, as a nsIFile object
  376.  */
  377. function getUpdatesDir(key) {
  378.   // Right now, we only support downloading one patch at a time, so we always
  379.   // use the same target directory.
  380.   var fileLocator = Cc["@mozilla.org/file/directory_service;1"].
  381.                     getService(Ci.nsIProperties);
  382.   var updateDir;
  383.   if (key)
  384.     updateDir = fileLocator.get(key, Ci.nsIFile);
  385.   else {
  386.     updateDir = fileLocator.get(KEY_APPDIR, Ci.nsIFile);
  387. //@line 366 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  388.   }
  389.   updateDir.append(DIR_UPDATES);
  390.   updateDir.append("0");
  391.   if (!updateDir.exists() && !key) {
  392.     LOG("General", "getUpdatesDir - update directory " + updateDir.path +
  393.         " doesn't exist, creating...");
  394.     updateDir.create(Ci.nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  395.   }
  396.   return updateDir;
  397. }
  398.  
  399. /**
  400.  * Reads the update state from the update.status file in the specified
  401.  * directory.
  402.  * @param   dir
  403.  *          The dir to look for an update.status file in
  404.  * @returns The status value of the update.
  405.  */
  406. function readStatusFile(dir) {
  407.   var statusFile = dir.clone();
  408.   statusFile.append(FILE_UPDATE_STATUS);
  409.   var status = readStringFromFile(statusFile) || STATE_NONE;
  410.   LOG("General", "readStatusFile - status: " + status + ", path: " +
  411.       statusFile.path);
  412.   return status;
  413. }
  414.  
  415. /**
  416.  * Writes the current update operation/state to a file in the patch
  417.  * directory, indicating to the patching system that operations need
  418.  * to be performed.
  419.  * @param   dir
  420.  *          The patch directory where the update.status file should be
  421.  *          written.
  422.  * @param   state
  423.  *          The state value to write.
  424.  */
  425. function writeStatusFile(dir, state) {
  426.   var statusFile = dir.clone();
  427.   statusFile.append(FILE_UPDATE_STATUS);
  428.   writeStringToFile(statusFile, state);
  429. }
  430.  
  431. /**
  432. //@line 424 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  433.  */
  434. function writeVersionFile(dir, version) {
  435.   var versionFile = dir.clone();
  436.   versionFile.append(FILE_UPDATE_VERSION);
  437.   writeStringToFile(versionFile, version);
  438. }
  439.  
  440. /**
  441.  * Removes the Updates Directory
  442.  * @param   key
  443.  *          The Directory Service Key under which update directory resides
  444.  *          (optional).
  445.  */
  446. function cleanUpUpdatesDir(key) {
  447.   // Bail out if we don't have appropriate permissions
  448.   var updateDir;
  449.   try {
  450.     updateDir = getUpdatesDir(key);
  451.   }
  452.   catch (e) {
  453.     return;
  454.   }
  455.  
  456.   var e = updateDir.directoryEntries;
  457.   while (e.hasMoreElements()) {
  458.     var f = e.getNext().QueryInterface(Ci.nsIFile);
  459.     // Preserve the last update log file for debugging purposes
  460.     if (f.leafName == FILE_UPDATE_LOG) {
  461.       try {
  462.         var dir = f.parent.parent;
  463.         var logFile = dir.clone();
  464.         logFile.append(FILE_LAST_LOG);
  465.         if (logFile.exists())
  466.           logFile.remove(false);
  467.         f.copyTo(dir, FILE_LAST_LOG);
  468.       }
  469.       catch (e) {
  470.         LOG("General", "cleanUpUpdatesDir - failed to copy file: " + f.path);
  471.       }
  472.     }
  473.     // Now, recursively remove this file.  The recusive removal is really
  474.     // only needed on Mac OSX because this directory will contain a copy of
  475.     // updater.app, which is itself a directory.
  476.     try {
  477.       f.remove(true);
  478.     }
  479.     catch (e) {
  480.       LOG("General", "cleanUpUpdatesDir - failed to remove file: " + f.path);
  481.     }
  482.   }
  483.   try {
  484.     updateDir.remove(false);
  485.   } catch (e) {
  486.     LOG("General", "cleanUpUpdatesDir - failed to remove update directory: " +
  487.         updateDir.path + " - This is almost always bad. Exception = " + e);
  488.     throw e;
  489.   }
  490.   LOG("General", "cleanUpUpdatesDir - successfully removed update directory: " +
  491.       updateDir.path);
  492. }
  493.  
  494. /**
  495.  * Clean up updates list and the updates directory.
  496.  * @param   key
  497.  *          The Directory Service Key under which update directory resides
  498.  *          (optional).
  499.  */
  500. function cleanupActiveUpdate(key) {
  501.   // Move the update from the Active Update list into the Past Updates list.
  502.   var um = Cc["@mozilla.org/updates/update-manager;1"].
  503.            getService(Ci.nsIUpdateManager);
  504.   um.activeUpdate = null;
  505.   um.saveUpdates();
  506.  
  507.   // Now trash the updates directory, since we're done with it
  508.   cleanUpUpdatesDir(key);
  509. }
  510.  
  511. /**
  512.  * Gets a preference value, handling the case where there is no default.
  513.  * @param   func
  514.  *          The name of the preference function to call, on nsIPrefBranch
  515.  * @param   preference
  516.  *          The name of the preference
  517.  * @param   defaultValue
  518.  *          The default value to return in the event the preference has
  519.  *          no setting
  520.  * @returns The value of the preference, or undefined if there was no
  521.  *          user or default value.
  522.  */
  523. function getPref(func, preference, defaultValue) {
  524.   try {
  525.     return gPref[func](preference);
  526.   }
  527.   catch (e) {
  528.   }
  529.   return defaultValue;
  530. }
  531.  
  532. /**
  533.  * Gets the locale from the update.locale file for replacing %LOCALE% in the
  534.  * update url. The update.locale file can be located in the application
  535.  * directory or the GRE directory with preference given to it being located in
  536.  * the application directory.
  537.  */
  538. function getLocale() {
  539.   if (gLocale)
  540.     return gLocale;
  541.  
  542.   var localeFile = getFile(KEY_APPDIR, [FILE_UPDATE_LOCALE]);
  543.   if (!localeFile.exists())
  544.     localeFile = getFile(KEY_GRED, [FILE_UPDATE_LOCALE]);
  545.  
  546.   if (!localeFile.exists())
  547.     throw Components.Exception(FILE_UPDATE_LOCALE + " file doesn't exist in " +
  548.                                "either the " + KEY_APPDIR + " or " + KEY_GRED +
  549.                                " directories", Cr.NS_ERROR_FILE_NOT_FOUND);
  550.  
  551.   gLocale = readStringFromFile(localeFile);
  552.   LOG("General", "getLocale - getting locale from file: " + localeFile.path +
  553.       ", locale: " + gLocale);
  554.   return gLocale;
  555. }
  556.  
  557. /**
  558.  * Read the update channel from defaults only.  We do this to ensure that
  559.  * the channel is tightly coupled with the application and does not apply
  560.  * to other instances of the application that may use the same profile.
  561.  */
  562. function getUpdateChannel() {
  563.   var channel = "default";
  564.   var prefName;
  565.   var prefValue;
  566.  
  567.   try {
  568.     channel = getDefaultPrefBranch().getCharPref(PREF_APP_UPDATE_CHANNEL);
  569.   } catch (e) {
  570.     // use default when pref not found
  571.   }
  572.  
  573.   try {
  574.     var partners = gPref.getChildList(PREF_PARTNER_BRANCH, { });
  575.     if (partners.length) {
  576.       channel += "-cck";
  577.       partners.sort();
  578.  
  579.       for each (prefName in partners) {
  580.         prefValue = gPref.getCharPref(prefName);
  581.         channel += "-" + prefValue;
  582.       }
  583.     }
  584.   }
  585.   catch (e) {
  586.     Components.utils.reportError(e);
  587.   }
  588.  
  589.   return channel;
  590. }
  591.  
  592. /* Get the distribution pref values, from defaults only */
  593. function getDistributionPrefValue(aPrefName) {
  594.   var prefValue = "default";
  595.  
  596.   try {
  597.     prefValue = getDefaultPrefBranch().getCharPref(aPrefName);
  598.   } catch (e) {
  599.     // use default when pref not found
  600.   }
  601.  
  602.   return prefValue;
  603. }
  604.  
  605. /**
  606.  * An enumeration of items in a JS array.
  607.  * @constructor
  608.  */
  609. function ArrayEnumerator(aItems) {
  610.   this._index = 0;
  611.   if (aItems) {
  612.     for (var i = 0; i < aItems.length; ++i) {
  613.       if (!aItems[i])
  614.         aItems.splice(i, 1);
  615.     }
  616.   }
  617.   this._contents = aItems;
  618. }
  619.  
  620. ArrayEnumerator.prototype = {
  621.   _index: 0,
  622.   _contents: [],
  623.  
  624.   hasMoreElements: function ArrayEnumerator_hasMoreElements() {
  625.     return this._index < this._contents.length;
  626.   },
  627.  
  628.   getNext: function ArrayEnumerator_getNext() {
  629.     return this._contents[this._index++];
  630.   }
  631. };
  632.  
  633. /**
  634.  * Trims a prefix from a string.
  635.  * @param   string
  636.  *          The source string
  637.  * @param   prefix
  638.  *          The prefix to remove.
  639.  * @returns The suffix (string - prefix)
  640.  */
  641. function stripPrefix(string, prefix) {
  642.   return string.substr(prefix.length);
  643. }
  644.  
  645. /**
  646.  * Writes a string of text to a file.  A newline will be appended to the data
  647.  * written to the file.  This function only works with ASCII text.
  648.  */
  649. function writeStringToFile(file, text) {
  650.   var fos = Cc["@mozilla.org/network/safe-file-output-stream;1"].
  651.             createInstance(Ci.nsIFileOutputStream);
  652.   var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  653.   if (!file.exists())
  654.     file.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  655.   fos.init(file, modeFlags, PERMS_FILE, 0);
  656.   text += "\n";
  657.   fos.write(text, text.length);
  658.   closeSafeOutputStream(fos);
  659. }
  660.  
  661. /**
  662.  * Reads a string of text from a file.  A trailing newline will be removed
  663.  * before the result is returned.  This function only works with ASCII text.
  664.  */
  665. function readStringFromFile(file) {
  666.   var fis = Cc["@mozilla.org/network/file-input-stream;1"].
  667.             createInstance(Ci.nsIFileInputStream);
  668.   var modeFlags = MODE_RDONLY;
  669.   if (!file.exists()) {
  670.     LOG("General", "readStringFromFile - file doesn't exist: " + file.path);
  671.     return null;
  672.   }
  673.   fis.init(file, modeFlags, PERMS_FILE, 0);
  674.   var sis = Cc["@mozilla.org/scriptableinputstream;1"].
  675.             createInstance(Ci.nsIScriptableInputStream);
  676.   sis.init(fis);
  677.   var text = sis.read(sis.available());
  678.   sis.close();
  679.   if (text[text.length - 1] == "\n")
  680.     text = text.slice(0, -1);
  681.   return text;
  682. }
  683.  
  684. function getObserverService()
  685. {
  686.   return Cc["@mozilla.org/observer-service;1"].
  687.          getService(Ci.nsIObserverService);
  688. }
  689.  
  690. function getDefaultPrefBranch()
  691. {
  692.   return gPref.QueryInterface(Ci.nsIPrefService).getDefaultBranch(null);
  693. }
  694. /**
  695.  * Update Patch
  696.  * @param   patch
  697.  *          A <patch> element to initialize this object with
  698.  * @throws if patch has a size of 0
  699.  * @constructor
  700.  */
  701. function UpdatePatch(patch) {
  702.   this._properties = {};
  703.   for (var i = 0; i < patch.attributes.length; ++i) {
  704.     var attr = patch.attributes.item(i);
  705.     attr.QueryInterface(Ci.nsIDOMAttr);
  706.     switch (attr.name) {
  707.     case "selected":
  708.       this.selected = attr.value == "true";
  709.       break;
  710.     case "size":
  711.       if (0 == parseInt(attr.value)) {
  712.         LOG("UpdatePatch", "init - 0-sized patch!");
  713.         throw Cr.NS_ERROR_ILLEGAL_VALUE;
  714.       }
  715.       // fall through
  716.     default:
  717.       this[attr.name] = attr.value;
  718.       break;
  719.     };
  720.   }
  721. }
  722. UpdatePatch.prototype = {
  723.   /**
  724.    * See nsIUpdateService.idl
  725.    */
  726.   serialize: function UpdatePatch_serialize(updates) {
  727.     var patch = updates.createElementNS(URI_UPDATE_NS, "patch");
  728.     patch.setAttribute("type", this.type);
  729.     patch.setAttribute("URL", this.URL);
  730.     patch.setAttribute("hashFunction", this.hashFunction);
  731.     patch.setAttribute("hashValue", this.hashValue);
  732.     patch.setAttribute("size", this.size);
  733.     patch.setAttribute("selected", this.selected);
  734.     patch.setAttribute("state", this.state);
  735.  
  736.     for (var p in this._properties) {
  737.       if (this._properties[p].present)
  738.         patch.setAttribute(p, this._properties[p].data);
  739.     }
  740.  
  741.     return patch;
  742.   },
  743.  
  744.   /**
  745.    * A hash of custom properties
  746.    */
  747.   _properties: null,
  748.  
  749.   /**
  750.    * See nsIWritablePropertyBag.idl
  751.    */
  752.   setProperty: function UpdatePatch_setProperty(name, value) {
  753.     this._properties[name] = { data: value, present: true };
  754.   },
  755.  
  756.   /**
  757.    * See nsIWritablePropertyBag.idl
  758.    */
  759.   deleteProperty: function UpdatePatch_deleteProperty(name) {
  760.     if (name in this._properties)
  761.       this._properties[name].present = false;
  762.     else
  763.       throw Cr.NS_ERROR_FAILURE;
  764.   },
  765.  
  766.   /**
  767.    * See nsIPropertyBag.idl
  768.    */
  769.   get enumerator() {
  770.     var properties = [];
  771.     for (var p in this._properties)
  772.       properties.push(this._properties[p].data);
  773.     return new ArrayEnumerator(properties);
  774.   },
  775.  
  776.   /**
  777.    * See nsIPropertyBag.idl
  778.    */
  779.   getProperty: function UpdatePatch_getProperty(name) {
  780.     if (name in this._properties &&
  781.         this._properties[name].present)
  782.       return this._properties[name].data;
  783.     throw Cr.NS_ERROR_FAILURE;
  784.   },
  785.  
  786.   /**
  787.    * Returns whether or not the update.status file for this patch exists at the
  788.    * appropriate location.
  789.    */
  790.   get statusFileExists() {
  791.     var statusFile = getUpdatesDir();
  792.     statusFile.append(FILE_UPDATE_STATUS);
  793.     return statusFile.exists();
  794.   },
  795.  
  796.   /**
  797.    * See nsIUpdateService.idl
  798.    */
  799.   get state() {
  800.     if (this._properties.state)
  801.       return this._properties.state;
  802.     return STATE_NONE;
  803.   },
  804.   set state(val) {
  805.     this._properties.state = val;
  806.   },
  807.  
  808.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdatePatch,
  809.                                          Ci.nsIPropertyBag,
  810.                                          Ci.nsIWritablePropertyBag])
  811. };
  812.  
  813. /**
  814.  * Update
  815.  * Implements nsIUpdate
  816.  * @param   update
  817.  *          An <update> element to initialize this object with
  818.  * @throws if the update contains no patches
  819.  * @constructor
  820.  */
  821. function Update(update) {
  822.   this._properties = {};
  823.   this._patches = [];
  824.   this.installDate = 0;
  825.   this.isCompleteUpdate = false;
  826.   this.channel = "default"
  827.  
  828.   // Null <update>, assume this is a message container and do no
  829.   // further initialization
  830.   if (!update)
  831.     return;
  832.  
  833.   const ELEMENT_NODE = Ci.nsIDOMNode.ELEMENT_NODE;
  834.   for (var i = 0; i < update.childNodes.length; ++i) {
  835.     var patchElement = update.childNodes.item(i);
  836.     if (patchElement.nodeType != ELEMENT_NODE ||
  837.         patchElement.localName != "patch")
  838.       continue;
  839.  
  840.     patchElement.QueryInterface(Ci.nsIDOMElement);
  841.     try {
  842.       var patch = new UpdatePatch(patchElement);
  843.     } catch (e) {
  844.       continue;
  845.     }
  846.     this._patches.push(patch);
  847.   }
  848.  
  849.   if (0 == this._patches.length)
  850.     throw Cr.NS_ERROR_ILLEGAL_VALUE;
  851.  
  852.   for (var i = 0; i < update.attributes.length; ++i) {
  853.     var attr = update.attributes.item(i);
  854.     attr.QueryInterface(Ci.nsIDOMAttr);
  855.     if (attr.name == "installDate" && attr.value)
  856.       this.installDate = parseInt(attr.value);
  857.     else if (attr.name == "isCompleteUpdate")
  858.       this.isCompleteUpdate = attr.value == "true";
  859.     else if (attr.name == "isSecurityUpdate")
  860.       this.isSecurityUpdate = attr.value == "true";
  861.     else if (attr.name == "detailsURL")
  862.       this._detailsURL = attr.value;
  863.     else if (attr.name == "channel")
  864.       this.channel = attr.value;
  865.     else
  866.       this[attr.name] = attr.value;
  867.   }
  868.  
  869.   // The Update Name is either the string provided by the <update> element, or
  870.   // the string: "<App Name> <Update App Version>"
  871.   var name = "";
  872.   if (update.hasAttribute("name"))
  873.     name = update.getAttribute("name");
  874.   else {
  875.     var sbs = Cc["@mozilla.org/intl/stringbundle;1"].
  876.               getService(Ci.nsIStringBundleService);
  877.     var brandBundle = sbs.createBundle(URI_BRAND_PROPERTIES);
  878.     var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  879.     var appName = brandBundle.GetStringFromName("brandShortName");
  880.     name = updateBundle.formatStringFromName("updateName",
  881.                                              [appName, this.version], 2);
  882.   }
  883.   this.name = name;
  884. }
  885. Update.prototype = {
  886.   /**
  887.    * See nsIUpdateService.idl
  888.    */
  889.   get patchCount() {
  890.     return this._patches.length;
  891.   },
  892.  
  893.   /**
  894.    * See nsIUpdateService.idl
  895.    */
  896.   getPatchAt: function Update_getPatchAt(index) {
  897.     return this._patches[index];
  898.   },
  899.  
  900.   /**
  901.    * See nsIUpdateService.idl
  902.    *
  903.    * We use a copy of the state cached on this object in |_state| only when
  904.    * there is no selected patch, i.e. in the case when we could not load
  905.    * |.activeUpdate| from the update manager for some reason but still have
  906.    * the update.status file to work with.
  907.    */
  908.   _state: "",
  909.   set state(state) {
  910.     if (this.selectedPatch)
  911.       this.selectedPatch.state = state;
  912.     this._state = state;
  913.     return state;
  914.   },
  915.   get state() {
  916.     if (this.selectedPatch)
  917.       return this.selectedPatch.state;
  918.     return this._state;
  919.   },
  920.  
  921.   /**
  922.    * See nsIUpdateService.idl
  923.    */
  924.   errorCode: 0,
  925.  
  926.   /**
  927.    * See nsIUpdateService.idl
  928.    */
  929.   get selectedPatch() {
  930.     for (var i = 0; i < this.patchCount; ++i) {
  931.       if (this._patches[i].selected)
  932.         return this._patches[i];
  933.     }
  934.     return null;
  935.   },
  936.  
  937.   /**
  938.    * See nsIUpdateService.idl
  939.    */
  940.   get detailsURL() {
  941.     if (!this._detailsURL) {
  942.       try {
  943.         // Try using a default details URL supplied by the distribution
  944.         // if the update XML does not supply one.
  945.         var formatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"].
  946.                         getService(Ci.nsIURLFormatter);
  947.         return formatter.formatURLPref(PREF_APP_UPDATE_URL_DETAILS);
  948.       }
  949.       catch (e) {
  950.       }
  951.     }
  952.     return this._detailsURL || "";
  953.   },
  954.  
  955.   /**
  956.    * See nsIUpdateService.idl
  957.    */
  958.   serialize: function Update_serialize(updates) {
  959.     var update = updates.createElementNS(URI_UPDATE_NS, "update");
  960.     update.setAttribute("type", this.type);
  961.     update.setAttribute("name", this.name);
  962.     update.setAttribute("version", this.version);
  963.     update.setAttribute("platformVersion", this.platformVersion);
  964.     update.setAttribute("extensionVersion", this.extensionVersion);
  965.     update.setAttribute("detailsURL", this.detailsURL);
  966.     update.setAttribute("licenseURL", this.licenseURL);
  967.     update.setAttribute("serviceURL", this.serviceURL);
  968.     update.setAttribute("installDate", this.installDate);
  969.     update.setAttribute("statusText", this.statusText);
  970.     update.setAttribute("buildID", this.buildID);
  971.     update.setAttribute("isCompleteUpdate", this.isCompleteUpdate);
  972.     update.setAttribute("channel", this.channel);
  973.     updates.documentElement.appendChild(update);
  974.  
  975.     for (var p in this._properties) {
  976.       if (this._properties[p].present)
  977.         update.setAttribute(p, this._properties[p].data);
  978.     }
  979.  
  980.     for (var i = 0; i < this.patchCount; ++i)
  981.       update.appendChild(this.getPatchAt(i).serialize(updates));
  982.  
  983.     return update;
  984.   },
  985.  
  986.   /**
  987.    * A hash of custom properties
  988.    */
  989.   _properties: null,
  990.  
  991.   /**
  992.    * See nsIWritablePropertyBag.idl
  993.    */
  994.   setProperty: function Update_setProperty(name, value) {
  995.     this._properties[name] = { data: value, present: true };
  996.   },
  997.  
  998.   /**
  999.    * See nsIWritablePropertyBag.idl
  1000.    */
  1001.   deleteProperty: function Update_deleteProperty(name) {
  1002.     if (name in this._properties)
  1003.       this._properties[name].present = false;
  1004.     else
  1005.       throw Cr.NS_ERROR_FAILURE;
  1006.   },
  1007.  
  1008.   /**
  1009.    * See nsIPropertyBag.idl
  1010.    */
  1011.   get enumerator() {
  1012.     var properties = [];
  1013.     for (var p in this._properties)
  1014.       properties.push(this._properties[p].data);
  1015.     return new ArrayEnumerator(properties);
  1016.   },
  1017.  
  1018.   /**
  1019.    * See nsIPropertyBag.idl
  1020.    */
  1021.   getProperty: function Update_getProperty(name) {
  1022.     if (name in this._properties &&
  1023.         this._properties[name].present)
  1024.       return this._properties[name].data;
  1025.     throw Cr.NS_ERROR_FAILURE;
  1026.   },
  1027.  
  1028.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdate,
  1029.                                          Ci.nsIPropertyBag,
  1030.                                          Ci.nsIWritablePropertyBag])
  1031. };
  1032.  
  1033. const UpdateServiceFactory = {
  1034.   _instance: null,
  1035.   createInstance: function (outer, iid) {
  1036.     if (outer != null)
  1037.       throw Components.results.NS_ERROR_NO_AGGREGATION;
  1038.     return this._instance == null ? this._instance = new UpdateService() :
  1039.                                     this._instance;
  1040.   }
  1041. };
  1042.  
  1043. /**
  1044.  * UpdateService
  1045.  * A Service for managing the discovery and installation of software updates.
  1046.  * @constructor
  1047.  */
  1048. function UpdateService() {
  1049.   gApp  = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo).
  1050.           QueryInterface(Ci.nsIXULRuntime);
  1051.   gPref = Cc["@mozilla.org/preferences-service;1"].
  1052.           getService(Ci.nsIPrefBranch2);
  1053.   gConsole = Cc["@mozilla.org/consoleservice;1"].
  1054.              getService(Ci.nsIConsoleService);
  1055.  
  1056.   // Not all builds have a known ABI
  1057.   try {
  1058.     gABI = gApp.XPCOMABI;
  1059.   }
  1060.   catch (e) {
  1061.     LOG("UpdateService", "init - XPCOM ABI unknown: updates are not possible.");
  1062.   }
  1063.  
  1064.   var osVersion;
  1065.   var sysInfo = Cc["@mozilla.org/system-info;1"].
  1066.                 getService(Ci.nsIPropertyBag2);
  1067.   try {
  1068.     osVersion = sysInfo.getProperty("name") + " " + sysInfo.getProperty("version");
  1069.   }
  1070.   catch (e) {
  1071.     LOG("UpdateService", "init - OS Version unknown: updates are not possible.");
  1072.   }
  1073.  
  1074.   if (osVersion) {
  1075.     try {
  1076.       osVersion += " (" + sysInfo.getProperty("secondaryLibrary") + ")";
  1077.     }
  1078.     catch (e) {
  1079.       // Not all platforms have a secondary widget library, so an error is nothing to worry about.
  1080.     }
  1081.     gOSVersion = encodeURIComponent(osVersion);
  1082.   }
  1083.  
  1084. //@line 1084 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1085.  
  1086.   // Start the update timer only after a profile has been selected so that the
  1087.   // appropriate values for the update check are read from the user's profile.
  1088.   var os = getObserverService();
  1089.  
  1090.   os.addObserver(this, "profile-after-change", false);
  1091.  
  1092.   // Observe xpcom-shutdown to unhook pref branch observers above to avoid
  1093.   // shutdown leaks.
  1094.   os.addObserver(this, "xpcom-shutdown", false);
  1095. }
  1096.  
  1097. UpdateService.prototype = {
  1098.   /**
  1099.    * The downloader we are using to download updates. There is only ever one of
  1100.    * these.
  1101.    */
  1102.   _downloader: null,
  1103.  
  1104.   /**
  1105.    * Incompatible add-on count.
  1106.    */
  1107.   _incompatAddonsCount: 0,
  1108.  
  1109.   /**
  1110.    * Handle Observer Service notifications
  1111.    * @param   subject
  1112.    *          The subject of the notification
  1113.    * @param   topic
  1114.    *          The notification name
  1115.    * @param   data
  1116.    *          Additional data
  1117.    */
  1118.   observe: function AUS_observe(subject, topic, data) {
  1119.     var os = getObserverService();
  1120.  
  1121.     switch (topic) {
  1122.     case "profile-after-change":
  1123.       os.removeObserver(this, "profile-after-change");
  1124.       os.addObserver(this, "final-ui-startup", false);
  1125.       this._start();
  1126.       break;
  1127.     case "final-ui-startup":
  1128.       os.removeObserver(this, "final-ui-startup");
  1129.       this._final_ui_start();
  1130.       break;
  1131.     case "xpcom-shutdown":
  1132.       os.removeObserver(this, "xpcom-shutdown");
  1133.  
  1134.       // Prevent leaking the downloader (bug 454964)
  1135.       this._downloader = null;
  1136.  
  1137.       // Release Services
  1138.       gApp      = null;
  1139.       gPref     = null;
  1140.       gConsole  = null;
  1141.       break;
  1142.     }
  1143.   },
  1144.  
  1145.   /**
  1146.    * Start the Update Service
  1147.    */
  1148.   _start: function AUS__start() {
  1149.     // Start logging
  1150.     this._initLoggingPrefs();
  1151.  
  1152.     // Register a background update check timer
  1153.     var tm = Cc["@mozilla.org/updates/timer-manager;1"].
  1154.              getService(Ci.nsIUpdateTimerManager);
  1155.     var interval = getPref("getIntPref", PREF_APP_UPDATE_INTERVAL, 86400);
  1156.     tm.registerTimer("background-update-timer", this, interval);
  1157.   },
  1158.  
  1159.   /**
  1160.    * The following needs to be performed after final-ui-startup (bug 497578)
  1161.    * 1. post update processing
  1162.    * 2. resume of a download that was in progress during a previous session
  1163.    * 3. start of a complete update download after the failure to apply a partial
  1164.    *    update
  1165.    */
  1166.   _final_ui_start: function AUS__delayed_start() {
  1167.     // Clean up any extant updates
  1168.     this._postUpdateProcessing();
  1169.  
  1170.     // Resume fetching...
  1171.     var um = Cc["@mozilla.org/updates/update-manager;1"].
  1172.              getService(Ci.nsIUpdateManager);
  1173.     var activeUpdate = um.activeUpdate;
  1174.     if (activeUpdate && activeUpdate.state != STATE_SUCCEEDED) {
  1175.       var status = this.downloadUpdate(activeUpdate, true);
  1176.       if (status == STATE_NONE)
  1177.         cleanupActiveUpdate();
  1178.     }
  1179.   },
  1180.  
  1181.   /**
  1182.    * Perform post-processing on updates lingering in the updates directory
  1183.    * from a previous browser session - either report install failures (and
  1184.    * optionally attempt to fetch a different version if appropriate) or
  1185.    * notify the user of install success.
  1186.    */
  1187.   _postUpdateProcessing: function AUS__postUpdateProcessing() {
  1188.     // Detect installation failures and notify
  1189.  
  1190.     // Bail out if we don't have appropriate permissions
  1191.     if (!this.canUpdate)
  1192.       return;
  1193.  
  1194.     var status = readStatusFile(getUpdatesDir());
  1195.  
  1196.     // Make sure to cleanup after an update that failed for an unknown reason
  1197.     if (status == "null")
  1198.       status = null;
  1199.  
  1200.     var updRootKey = null;
  1201. //@line 1222 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1202.  
  1203.     if (status == STATE_DOWNLOADING) {
  1204.       LOG("UpdateService", "_postUpdateProcessing - patch found in " +
  1205.           "downloading state");
  1206.     }
  1207.     else if (status != null) {
  1208.       // null status means the update.status file is not present, because either:
  1209.       // 1) no update was performed, and so there's no UI to show
  1210.       // 2) an update was attempted but failed during checking, transfer or
  1211.       //    verification, and was cleaned up at that point, and UI notifying of
  1212.       //    that error was shown at that stage.
  1213.       var um = Cc["@mozilla.org/updates/update-manager;1"].
  1214.                getService(Ci.nsIUpdateManager);
  1215.       var prompter = Cc["@mozilla.org/updates/update-prompt;1"].
  1216.                      createInstance(Ci.nsIUpdatePrompt);
  1217.  
  1218.       var update = um.activeUpdate;
  1219.       if (!update) {
  1220.         update = new Update(null);
  1221.       }
  1222.       update.state = status;
  1223.       var sbs = Cc["@mozilla.org/intl/stringbundle;1"].
  1224.                 getService(Ci.nsIStringBundleService);
  1225.       var bundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  1226.       if (status == STATE_SUCCEEDED) {
  1227.         update.statusText = bundle.GetStringFromName("installSuccess");
  1228.  
  1229.         // Update the patch's metadata.
  1230.         um.activeUpdate = update;
  1231.  
  1232.         prompter.showUpdateInstalled();
  1233. //@line 1257 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1234.         // Perform platform-specific post-update processing.
  1235.         if (POST_UPDATE_CONTRACTID in Cc) {
  1236.           Cc[POST_UPDATE_CONTRACTID].createInstance(Ci.nsIRunnable).run();
  1237.         }
  1238. //@line 1262 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1239.         // Done with this update. Clean it up.
  1240.         cleanupActiveUpdate(updRootKey);
  1241.       }
  1242.       else {
  1243.         // If we hit an error, then the error code will be included in the
  1244.         // status string following a colon.  If we had an I/O error, then we
  1245.         // assume that the patch is not invalid, and we restage the patch so
  1246.         // that it can be attempted again the next time we restart.
  1247.         var ary = status.split(": ");
  1248.         update.state = ary[0];
  1249.         if (update.state == STATE_FAILED && ary[1]) {
  1250.           update.errorCode = ary[1];
  1251.           if (update.errorCode == WRITE_ERROR) {
  1252.             prompter.showUpdateError(update);
  1253.             writeStatusFile(getUpdatesDir(), update.state = STATE_PENDING);
  1254.             writeVersionFile(getUpdatesDir(), update.extensionVersion);
  1255.             return;
  1256.           }
  1257.         }
  1258.  
  1259.         // Something went wrong with the patch application process.
  1260.         cleanupActiveUpdate();
  1261.  
  1262.         update.statusText = bundle.GetStringFromName("patchApplyFailure");
  1263.         var oldType = update.selectedPatch ? update.selectedPatch.type
  1264.                                            : "complete";
  1265.         if (update.selectedPatch && oldType == "partial") {
  1266.           // Partial patch application failed, try downloading the complete
  1267.           // update in the background instead.
  1268.           LOG("UpdateService", "_postUpdateProcessing - install of partial " +
  1269.               "patch failed, downloading complete patch");
  1270.           var status = this.downloadUpdate(update, true);
  1271.           if (status == STATE_NONE)
  1272.             cleanupActiveUpdate();
  1273.         }
  1274.         else {
  1275.           LOG("UpdateService", "_postUpdateProcessing - install of complete or " +
  1276.               "only one patch offered failed... showing error.");
  1277.         }
  1278.         update.QueryInterface(Ci.nsIWritablePropertyBag);
  1279.         update.setProperty("patchingFailed", oldType);
  1280.         prompter.showUpdateError(update);
  1281.       }
  1282.     }
  1283.     else {
  1284.       LOG("UpdateService", "_postUpdateProcessing - no status, no update");
  1285.     }
  1286.   },
  1287.  
  1288.   /**
  1289.    * Initialize Logging preferences, formatted like so:
  1290.    *  app.update.log.<moduleName> = <true|false>
  1291.    */
  1292.   _initLoggingPrefs: function AUS__initLoggingPrefs() {
  1293.     try {
  1294.       var ps = Cc["@mozilla.org/preferences-service;1"].
  1295.                getService(Ci.nsIPrefService);
  1296.       var logBranch = ps.getBranch(PREF_APP_UPDATE_LOG_BRANCH);
  1297.       var modules = logBranch.getChildList("", { value: 0 });
  1298.  
  1299.       for (var i = 0; i < modules.length; ++i) {
  1300.         if (logBranch.prefHasUserValue(modules[i]))
  1301.           gLogEnabled[modules[i]] = logBranch.getBoolPref(modules[i]);
  1302.       }
  1303.     }
  1304.     catch (e) {
  1305.     }
  1306.   },
  1307.  
  1308.   /**
  1309.    * Notified when a timer fires
  1310.    * @param   timer
  1311.    *          The timer that fired
  1312.    */
  1313.   notify: function AUS_notify(timer) {
  1314.     // If a download is in progress or the patch has been staged do nothing.
  1315.     if (this.isDownloading || this._downloader && this._downloader.patchIsStaged)
  1316.       return;
  1317.  
  1318.     var self = this;
  1319.     var listener = {
  1320.       /**
  1321.        * See nsIUpdateService.idl
  1322.        */
  1323.       onProgress: function AUS_notify_onProgress(request, position, totalSize) {
  1324.       },
  1325.  
  1326.       /**
  1327.        * See nsIUpdateService.idl
  1328.        */
  1329.       onCheckComplete: function AUS_notify_onCheckComplete(request, updates,
  1330.                                                            updateCount) {
  1331.         self._selectAndInstallUpdate(updates);
  1332.       },
  1333.  
  1334.       /**
  1335.        * See nsIUpdateService.idl
  1336.        */
  1337.       onError: function AUS_notify_onError(request, update) {
  1338.         LOG("UpdateService", "notify:listener - error during background " +
  1339.             "update: " + update.statusText);
  1340.       },
  1341.     }
  1342.     this.backgroundChecker.checkForUpdates(listener, false);
  1343.   },
  1344.  
  1345.   /**
  1346.    * Determine which of the specified updates should be installed.
  1347.    * @param   updates
  1348.    *          An array of available updates
  1349.    */
  1350.   selectUpdate: function AUS_selectUpdate(updates) {
  1351.     if (updates.length == 0)
  1352.       return null;
  1353.  
  1354.     // Choose the newest of the available minor and major updates.
  1355.     var majorUpdate = null, minorUpdate = null;
  1356.     var newestMinor = updates[0], newestMajor = updates[0];
  1357.  
  1358.     var vc = Cc["@mozilla.org/xpcom/version-comparator;1"].
  1359.              getService(Ci.nsIVersionComparator);
  1360.     for (var i = 0; i < updates.length; ++i) {
  1361.       // Ignore updates for older versions of the application
  1362.       if (vc.compare(updates[i].extensionVersion, gApp.version) < 0)
  1363.         continue;
  1364.       if (updates[i].type == "major" &&
  1365.           vc.compare(newestMajor.version, updates[i].version) <= 0)
  1366.         majorUpdate = newestMajor = updates[i];
  1367.       if (updates[i].type == "minor" &&
  1368.           vc.compare(newestMinor.version, updates[i].version) <= 0)
  1369.         minorUpdate = newestMinor = updates[i];
  1370.     }
  1371.  
  1372.     // IMPORTANT
  1373.     // If there's a minor update, always try and fetch that one first,
  1374.     // otherwise use the newest major update.
  1375.     // selectUpdate() only returns one update.
  1376.     // if major were to trump minor, and we said "never" to the major
  1377.     // we'd never get the minor update, since selectUpdate()
  1378.     // would return the major update that the user said "never" to
  1379.     // (shadowing the important minor update with security fixes)
  1380.     return minorUpdate || majorUpdate;
  1381.   },
  1382.  
  1383.   /**
  1384.    * Reference to the currently selected update for when add-on compatibility
  1385.    * is checked.
  1386.    */
  1387.   _update: null,
  1388.  
  1389.   /**
  1390.    * Determine which of the specified updates should be installed and begin the
  1391.    * download/installation process or notify the user about the update.
  1392.    * @param   updates
  1393.    *          An array of available updates
  1394.    */
  1395.   _selectAndInstallUpdate: function AUS__selectAndInstallUpdate(updates) {
  1396.     // Return early if there's an active update. The user is already aware and
  1397.     // is downloading or performed some user action to prevent notification.
  1398.     var um = Cc["@mozilla.org/updates/update-manager;1"].
  1399.              getService(Ci.nsIUpdateManager);
  1400.     if (um.activeUpdate)
  1401.       return;
  1402.  
  1403.     var update = this.selectUpdate(updates, updates.length);
  1404.     if (!update)
  1405.       return;
  1406.  
  1407.     var updateEnabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1408.     if (!updateEnabled) {
  1409.       LOG("Checker", "_selectAndInstallUpdate - not prompting because update " +
  1410.           "is disabled");
  1411.       return;
  1412.     }
  1413.  
  1414.     /**
  1415. //@line 1450 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1416.      */
  1417.  
  1418.     // Encode version since it could be a non-ascii string (bug 359093)
  1419.     var neverPrefName = PREF_UPDATE_NEVER_BRANCH +
  1420.                         encodeURIComponent(update.version);
  1421.     if (update.type == "major" &&
  1422.         getPref("getBoolPref", neverPrefName, false)) {
  1423.       LOG("Checker", "_selectAndInstallUpdate - not prompting because this " +
  1424.           "is a major update and the preference " + neverPrefName + " is true");
  1425.       return;
  1426.     }
  1427.  
  1428.     /**
  1429. //@line 1479 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1430.      */
  1431.     if (update.type == "major") {
  1432.       LOG("Checker", "_selectAndInstallUpdate - prompting because it is a " +
  1433.           "major update");
  1434.       this._showPrompt(update);
  1435.       return;
  1436.     }
  1437.  
  1438.     if (!getPref("getBoolPref", PREF_APP_UPDATE_AUTO, true)) {
  1439.       LOG("Checker", "_selectAndInstallUpdate - prompting because silent " +
  1440.           "install is disabled");
  1441.       this._showPrompt(update);
  1442.       return;
  1443.     }
  1444.  
  1445.     if (getPref("getIntPref", PREF_APP_UPDATE_MODE, 1) == 0) {
  1446.       // Do not prompt regardless of add-on incompatibilities
  1447.       LOG("UpdateService", "_selectAndInstallUpdate - no need to show " +
  1448.           "prompt, just download the update");
  1449.       var status = this.downloadUpdate(update, true);
  1450.       if (status == STATE_NONE)
  1451.         cleanupActiveUpdate();
  1452.       return;
  1453.     }
  1454.  
  1455.     var ai = Cc["@mozilla.org/xre/app-info;1"].
  1456.              getService(Ci.nsIXULAppInfo);
  1457.     var vc = Cc["@mozilla.org/xpcom/version-comparator;1"].
  1458.              getService(Ci.nsIVersionComparator);
  1459.     if (update.extensionVersion &&
  1460.         vc.compare(update.extensionVersion, ai.version) != 0) {
  1461.       this._update = update;
  1462.       this._checkAddonCompatibility();
  1463.     }
  1464.     else {
  1465.       LOG("UpdateService", "_selectAndInstallUpdate - no need to show " +
  1466.           "prompt, just download the update");
  1467.       var status = this.downloadUpdate(update, true);
  1468.       if (status == STATE_NONE)
  1469.         cleanupActiveUpdate();
  1470.     }
  1471.   },
  1472.  
  1473.   _showPrompt: function AUS__showPrompt(update) {
  1474.     var prompter = Cc["@mozilla.org/updates/update-prompt;1"].
  1475.                    createInstance(Ci.nsIUpdatePrompt);
  1476.     prompter.showUpdateAvailable(update);
  1477.   },
  1478.  
  1479.   _checkAddonCompatibility: function AUS__checkAddonCompatibility() {
  1480.     var em = Cc["@mozilla.org/extensions/manager;1"].
  1481.                getService(Ci.nsIExtensionManager);
  1482.     // Get the add-ons that are incompatible with the update's application
  1483.     // version and toolkit version.
  1484.     var currentAddons = em.getIncompatibleItemList("", this._update.extensionVersion,
  1485.                                                    this._update.platformVersion,
  1486.                                                    Ci.nsIUpdateItem.TYPE_ANY,
  1487.                                                    false, { });
  1488.     if (currentAddons.length > 0) {
  1489.       // Get the add-ons that are incompatible with the current application
  1490.       // version and toolkit version.
  1491.       var previousAddons = em.getIncompatibleItemList("", null, null,
  1492.                                                       Ci.nsIUpdateItem.TYPE_ANY,
  1493.                                                       false, { });
  1494.       // Don't include add-ons that are already incompatible with the current
  1495.       // application version and toolkit version.
  1496.       for (var i = 0; i < previousAddons.length; ++i) {
  1497.         for (var j = 0; j < currentAddons.length; ++j) {
  1498.           if (previousAddons[i].id === currentAddons[j].id) {
  1499.             currentAddons.splice(j, 1);
  1500.             break;
  1501.           }
  1502.         }
  1503.       }
  1504.     }
  1505.  
  1506.     if (currentAddons.length > 0) {
  1507.       /**
  1508. //@line 1575 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1509.        */
  1510.       this._incompatAddonsCount = currentAddons.length;
  1511.       LOG("UpdateService", "_checkAddonCompatibility - checking for " +
  1512.           "incompatible add-ons");
  1513.       var updateIncompatMode = getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE, 0);
  1514.       var mode = (updateIncompatMode == 1) ? Ci.nsIExtensionManager.UPDATE_CHECK_COMPATIBILITY :
  1515.                                              Ci.nsIExtensionManager.UPDATE_NOTIFY_NEWVERSION;
  1516.       em.update(currentAddons, currentAddons.length, mode, this,
  1517.                 this._update.extensionVersion, this._update.platformVersion);
  1518.     }
  1519.     else {
  1520.       LOG("UpdateService", "_checkAddonCompatibility - no need to show " +
  1521.           "prompt, just download the update");
  1522.       var status = this.downloadUpdate(this._update, true);
  1523.       if (status == STATE_NONE)
  1524.         cleanupActiveUpdate();
  1525.       this._update = null;
  1526.     }
  1527.   },
  1528.  
  1529.   /**
  1530.    * See nsIExtensionManager.idl
  1531.    */
  1532.   onUpdateStarted: function AUS_onUpdateStarted() {
  1533.   },
  1534.  
  1535.   /**
  1536.    * See nsIExtensionManager.idl
  1537.    */
  1538.   onUpdateEnded: function AUS_onUpdateEnded() {
  1539.     if (this._incompatAddonsCount > 0) {
  1540.       LOG("Checker", "onUpdateEnded - prompting because there are " +
  1541.           "incompatible add-ons");
  1542.       this._showPrompt(this._update);
  1543.     }
  1544.     else {
  1545.       LOG("UpdateService", "onUpdateEnded - no need to show prompt, just " +
  1546.           "download the update");
  1547.       var status = this.downloadUpdate(this._update, true);
  1548.       if (status == STATE_NONE)
  1549.         cleanupActiveUpdate();
  1550.     }
  1551.     this._update = null;
  1552.   },
  1553.  
  1554.   /**
  1555.    * See nsIExtensionManager.idl
  1556.    */
  1557.   onAddonUpdateStarted: function AUS_onAddonUpdateStarted(addon) {
  1558.   },
  1559.  
  1560.   /**
  1561.    * See nsIExtensionManager.idl
  1562.    */
  1563.   onAddonUpdateEnded: function AUS_onAddonUpdateEnded(addon, status) {
  1564.     if (status != Ci.nsIAddonUpdateCheckListener.STATUS_UPDATE &&
  1565.         status != Ci.nsIAddonUpdateCheckListener.STATUS_VERSIONINFO)
  1566.       return;
  1567.  
  1568.     LOG("UpdateService", "onAddonUpdateEnded - found update for add-on ID: " +
  1569.         addon.id);
  1570.     --this._incompatAddonsCount;
  1571.   },
  1572.  
  1573.   /**
  1574.    * The Checker used for background update checks.
  1575.    */
  1576.   _backgroundChecker: null,
  1577.  
  1578.   /**
  1579.    * See nsIUpdateService.idl
  1580.    */
  1581.   get backgroundChecker() {
  1582.     if (!this._backgroundChecker)
  1583.       this._backgroundChecker = new Checker();
  1584.     return this._backgroundChecker;
  1585.   },
  1586.  
  1587.   /**
  1588.    * See nsIUpdateService.idl
  1589.    */
  1590.   get canUpdate() {
  1591.     if (gCanUpdate !== null)
  1592.       return gCanUpdate;
  1593.  
  1594.     try {
  1595.       var appDirFile = getUpdateFile([FILE_PERMS_TEST]);
  1596.       LOG("UpdateService", "canUpdate - testing " + appDirFile.path);
  1597.       if (!appDirFile.exists()) {
  1598.         appDirFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1599.         appDirFile.remove(false);
  1600.       }
  1601.       var updateDir = getUpdatesDir();
  1602.       var upDirFile = updateDir.clone();
  1603.       upDirFile.append(FILE_PERMS_TEST);
  1604.       LOG("UpdateService", "canUpdate - testing " + upDirFile.path);
  1605.       if (!upDirFile.exists()) {
  1606.         upDirFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1607.         upDirFile.remove(false);
  1608.       }
  1609. //@line 1751 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1610.     }
  1611.     catch (e) {
  1612.        LOG("UpdateService", "canUpdate - unable to update. Exception: " + e);
  1613.       // No write privileges to install directory
  1614.       return gCanUpdate = false;
  1615.     }
  1616.     // If the administrator has locked the app update functionality
  1617.     // OFF - this is not just a user setting, so disable the manual
  1618.     // UI too.
  1619.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1620.     if (!enabled && gPref.prefIsLocked(PREF_APP_UPDATE_ENABLED)) {
  1621.       LOG("UpdateService", "canUpdate - unable to update, disabled by pref");
  1622.       return gCanUpdate = false;
  1623.     }
  1624.  
  1625.     // If we don't know the binary platform we're updating, we can't update.
  1626.     if (!gABI) {
  1627.       LOG("UpdateService", "canUpdate - unable tp update, unknown ABI");
  1628.       return gCanUpdate = false;
  1629.     }
  1630.  
  1631.     // If we don't know the OS version we're updating, we can't update.
  1632.     if (!gOSVersion) {
  1633.       LOG("UpdateService", "canUpdate unable to update, unknown OS version");
  1634.       return gCanUpdate = false;
  1635.     }
  1636.  
  1637.     LOG("UpdateService", "canUpdate - able to update");
  1638.     return gCanUpdate = true;
  1639.   },
  1640.  
  1641.   /**
  1642.    * See nsIUpdateService.idl
  1643.    */
  1644.   addDownloadListener: function AUS_addDownloadListener(listener) {
  1645.     if (!this._downloader) {
  1646.       LOG("UpdateService", "addDownloadListener - no downloader!");
  1647.       return;
  1648.     }
  1649.     this._downloader.addDownloadListener(listener);
  1650.   },
  1651.  
  1652.   /**
  1653.    * See nsIUpdateService.idl
  1654.    */
  1655.   removeDownloadListener: function AUS_removeDownloadListener(listener) {
  1656.     if (!this._downloader) {
  1657.       LOG("UpdateService", "removeDownloadListener - no downloader!");
  1658.       return;
  1659.     }
  1660.     this._downloader.removeDownloadListener(listener);
  1661.   },
  1662.  
  1663.   /**
  1664.    * See nsIUpdateService.idl
  1665.    */
  1666.   downloadUpdate: function AUS_downloadUpdate(update, background) {
  1667.     if (!update)
  1668.       throw Cr.NS_ERROR_NULL_POINTER;
  1669.  
  1670.     let ai = Cc["@mozilla.org/xre/app-info;1"].
  1671.              getService(Ci.nsIXULAppInfo);
  1672.     let vc = Cc["@mozilla.org/xpcom/version-comparator;1"].
  1673.              getService(Ci.nsIVersionComparator);
  1674.     // Don't download the update if the update's version is less than the
  1675.     // current application's version.
  1676.     if (update.extensionVersion && vc.compare(update.extensionVersion, ai.version) < 0) {
  1677.       LOG("UpdateService", "downloadUpdate - removing update for previous " +
  1678.           "application version " + update.extensionVersion);
  1679.       cleanupActiveUpdate();
  1680.       return STATE_NONE;
  1681.     }
  1682.  
  1683.     if (this.isDownloading) {
  1684.       if (update.isCompleteUpdate == this._downloader.isCompleteUpdate &&
  1685.           background == this._downloader.background) {
  1686.         LOG("UpdateService", "downloadUpdate - no support for downloading " +
  1687.             "more than one update at a time");
  1688.         return readStatusFile(getUpdatesDir());
  1689.       }
  1690.       this._downloader.cancel();
  1691.     }
  1692.     this._downloader = new Downloader(background);
  1693.     return this._downloader.downloadUpdate(update);
  1694.   },
  1695.  
  1696.   /**
  1697.    * See nsIUpdateService.idl
  1698.    */
  1699.   pauseDownload: function AUS_pauseDownload() {
  1700.     if (this.isDownloading)
  1701.       this._downloader.cancel();
  1702.   },
  1703.  
  1704.   /**
  1705.    * See nsIUpdateService.idl
  1706.    */
  1707.   get isDownloading() {
  1708.     return this._downloader && this._downloader.isBusy;
  1709.   },
  1710.  
  1711.   // nsIClassInfo
  1712.   flags: Ci.nsIClassInfo.SINGLETON,
  1713.   implementationLanguage: Ci.nsIProgrammingLanguage.JAVASCRIPT,
  1714.   getHelperForLanguage: function(language) null,
  1715.   getInterfaces: function AUS_getInterfaces(count) {
  1716.     var interfaces = [Ci.nsIApplicationUpdateService, Ci.nsITimerCallback,
  1717.                       Ci.nsIObserver];
  1718.     count.value = interfaces.length;
  1719.     return interfaces;
  1720.   },
  1721.  
  1722.   classDescription: "Update Service",
  1723.   contractID: "@mozilla.org/updates/update-service;1",
  1724.   classID: Components.ID("{B3C290A6-3943-4B89-8BBE-C01EB7B3B311}"),
  1725.   _xpcom_categories: [{ category: "app-startup", service: true }],
  1726.   _xpcom_factory: UpdateServiceFactory,
  1727.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIApplicationUpdateService,
  1728.                                          Ci.nsIAddonUpdateCheckListener,
  1729.                                          Ci.nsITimerCallback,
  1730.                                          Ci.nsIObserver])
  1731. };
  1732.  
  1733. /**
  1734.  * A service to manage active and past updates.
  1735.  * @constructor
  1736.  */
  1737. function UpdateManager() {
  1738.   // Ensure the Active Update file is loaded
  1739.   var updates = this._loadXMLFileIntoArray(getUpdateFile([FILE_UPDATE_ACTIVE]));
  1740.   if (updates.length > 0)
  1741.     this._activeUpdate = updates[0];
  1742. }
  1743. UpdateManager.prototype = {
  1744.   /**
  1745.    * All previously downloaded and installed updates, as an array of nsIUpdate
  1746.    * objects.
  1747.    */
  1748.   _updates: null,
  1749.  
  1750.   /**
  1751.    * The current actively downloading/installing update, as a nsIUpdate object.
  1752.    */
  1753.   _activeUpdate: null,
  1754.  
  1755.   /**
  1756.    * Loads an updates.xml formatted file into an array of nsIUpdate items.
  1757.    * @param   file
  1758.    *          A nsIFile for the updates.xml file
  1759.    * @returns The array of nsIUpdate items held in the file.
  1760.    */
  1761.   _loadXMLFileIntoArray: function UM__loadXMLFileIntoArray(file) {
  1762.     if (!file.exists()) {
  1763.       LOG("UpdateManager", "_loadXMLFileIntoArray: XML file does not exist");
  1764.       return [];
  1765.     }
  1766.  
  1767.     var result = [];
  1768.     var fileStream = Cc["@mozilla.org/network/file-input-stream;1"].
  1769.                      createInstance(Ci.nsIFileInputStream);
  1770.     fileStream.init(file, MODE_RDONLY, PERMS_FILE, 0);
  1771.     try {
  1772.       var parser = Cc["@mozilla.org/xmlextras/domparser;1"].
  1773.                    createInstance(Ci.nsIDOMParser);
  1774.       var doc = parser.parseFromStream(fileStream, "UTF-8",
  1775.                                        fileStream.available(), "text/xml");
  1776.  
  1777.       const ELEMENT_NODE = Ci.nsIDOMNode.ELEMENT_NODE;
  1778.       var updateCount = doc.documentElement.childNodes.length;
  1779.       for (var i = 0; i < updateCount; ++i) {
  1780.         var updateElement = doc.documentElement.childNodes.item(i);
  1781.         if (updateElement.nodeType != ELEMENT_NODE ||
  1782.             updateElement.localName != "update")
  1783.           continue;
  1784.  
  1785.         updateElement.QueryInterface(Ci.nsIDOMElement);
  1786.         try {
  1787.           var update = new Update(updateElement);
  1788.         } catch (e) {
  1789.           LOG("UpdateManager", "_loadXMLFileIntoArray - invalid update");
  1790.           continue;
  1791.         }
  1792.         result.push(update);
  1793.       }
  1794.     }
  1795.     catch (e) {
  1796.       LOG("UpdateManager", "_loadXMLFileIntoArray - error constructing " +
  1797.           "update list. Exception: " + e);
  1798.     }
  1799.     fileStream.close();
  1800.     return result;
  1801.   },
  1802.  
  1803.   /**
  1804.    * Load the update manager, initializing state from state files.
  1805.    */
  1806.   _ensureUpdates: function UM__ensureUpdates() {
  1807.     if (!this._updates) {
  1808.       this._updates = this._loadXMLFileIntoArray(getUpdateFile(
  1809.                         [FILE_UPDATES_DB]));
  1810.  
  1811.       var activeUpdates = this._loadXMLFileIntoArray(getUpdateFile(
  1812.                             [FILE_UPDATE_ACTIVE]));
  1813.       if (activeUpdates.length > 0)
  1814.         this._activeUpdate = activeUpdates[0];
  1815.     }
  1816.   },
  1817.  
  1818.   /**
  1819.    * See nsIUpdateService.idl
  1820.    */
  1821.   getUpdateAt: function UM_getUpdateAt(index) {
  1822.     this._ensureUpdates();
  1823.     return this._updates[index];
  1824.   },
  1825.  
  1826.   /**
  1827.    * See nsIUpdateService.idl
  1828.    */
  1829.   get updateCount() {
  1830.     this._ensureUpdates();
  1831.     return this._updates.length;
  1832.   },
  1833.  
  1834.   /**
  1835.    * See nsIUpdateService.idl
  1836.    */
  1837.   get activeUpdate() {
  1838.     if (this._activeUpdate &&
  1839.         this._activeUpdate.channel != getUpdateChannel()) {
  1840.       // User switched channels, clear out any old active updates and remove
  1841.       // partial downloads
  1842.       this._activeUpdate = null;
  1843.  
  1844.       // Destroy the updates directory, since we're done with it.
  1845.       cleanUpUpdatesDir();
  1846.     }
  1847.     return this._activeUpdate;
  1848.   },
  1849.   set activeUpdate(activeUpdate) {
  1850.     this._addUpdate(activeUpdate);
  1851.     this._activeUpdate = activeUpdate;
  1852.     if (!activeUpdate) {
  1853.       // If |activeUpdate| is null, we have updated both lists - the active list
  1854.       // and the history list, so we want to write both files.
  1855.       this.saveUpdates();
  1856.     }
  1857.     else
  1858.       this._writeUpdatesToXMLFile([this._activeUpdate],
  1859.                                   getUpdateFile([FILE_UPDATE_ACTIVE]));
  1860.     return activeUpdate;
  1861.   },
  1862.  
  1863.   /**
  1864.    * Add an update to the Updates list. If the item already exists in the list,
  1865.    * replace the existing value with the new value.
  1866.    * @param   update
  1867.    *          The nsIUpdate object to add.
  1868.    */
  1869.   _addUpdate: function UM__addUpdate(update) {
  1870.     if (!update)
  1871.       return;
  1872.     this._ensureUpdates();
  1873.     if (this._updates) {
  1874.       for (var i = 0; i < this._updates.length; ++i) {
  1875.         if (this._updates[i] &&
  1876.             this._updates[i].version == update.version &&
  1877.             this._updates[i].buildID == update.buildID) {
  1878.           // Replace the existing entry with the new value, updating
  1879.           // all metadata.
  1880.           this._updates[i] = update;
  1881.           return;
  1882.         }
  1883.       }
  1884.     }
  1885.     // Otherwise add it to the front of the list.
  1886.     this._updates.unshift(update);
  1887.   },
  1888.  
  1889.   /**
  1890.    * Serializes an array of updates to an XML file
  1891.    * @param   updates
  1892.    *          An array of nsIUpdate objects
  1893.    * @param   file
  1894.    *          The nsIFile object to serialize to
  1895.    */
  1896.   _writeUpdatesToXMLFile: function UM__writeUpdatesToXMLFile(updates, file) {
  1897.     var fos = Cc["@mozilla.org/network/safe-file-output-stream;1"].
  1898.               createInstance(Ci.nsIFileOutputStream);
  1899.     var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  1900.     if (!file.exists())
  1901.       file.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1902.     fos.init(file, modeFlags, PERMS_FILE, 0);
  1903.  
  1904.     try {
  1905.       var parser = Cc["@mozilla.org/xmlextras/domparser;1"].
  1906.                    createInstance(Ci.nsIDOMParser);
  1907.       const EMPTY_UPDATES_DOCUMENT = "<?xml version=\"1.0\"?><updates xmlns=\"http://www.mozilla.org/2005/app-update\"></updates>";
  1908.       var doc = parser.parseFromString(EMPTY_UPDATES_DOCUMENT, "text/xml");
  1909.  
  1910.       for (var i = 0; i < updates.length; ++i) {
  1911.         if (updates[i])
  1912.           doc.documentElement.appendChild(updates[i].serialize(doc));
  1913.       }
  1914.  
  1915.       var serializer = Cc["@mozilla.org/xmlextras/xmlserializer;1"].
  1916.                        createInstance(Ci.nsIDOMSerializer);
  1917.       serializer.serializeToStream(doc.documentElement, fos, null);
  1918.     }
  1919.     catch (e) {
  1920.     }
  1921.  
  1922.     closeSafeOutputStream(fos);
  1923.   },
  1924.  
  1925.   /**
  1926.    * See nsIUpdateService.idl
  1927.    */
  1928.   saveUpdates: function UM_saveUpdates() {
  1929.     this._writeUpdatesToXMLFile([this._activeUpdate],
  1930.                                 getUpdateFile([FILE_UPDATE_ACTIVE]));
  1931.     if (this._activeUpdate)
  1932.       this._addUpdate(this._activeUpdate);
  1933.  
  1934.     // Don't write updates that have a temporary state to the updates.xml file.
  1935.     if (this._updates) {
  1936.       let updates = this._updates.slice();
  1937.       for (let i = updates.length - 1; i >= 0; --i) {
  1938.         let state = updates[i].state;
  1939.         if (state == STATE_NONE || state == STATE_DOWNLOADING ||
  1940.             state == STATE_PENDING) {
  1941.           updates.splice(i, 1);
  1942.         }
  1943.       }
  1944.  
  1945.       this._writeUpdatesToXMLFile(updates.slice(0, 10),
  1946.                                   getUpdateFile([FILE_UPDATES_DB]));
  1947.     }
  1948.   },
  1949.  
  1950.   classDescription: "Update Manager",
  1951.   contractID: "@mozilla.org/updates/update-manager;1",
  1952.   classID: Components.ID("{093C2356-4843-4C65-8709-D7DBCBBE7DFB}"),
  1953.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdateManager])
  1954. };
  1955.  
  1956.  
  1957. /**
  1958.  * Checker
  1959.  * Checks for new Updates
  1960.  * @constructor
  1961.  */
  1962. function Checker() {
  1963. }
  1964. Checker.prototype = {
  1965.   /**
  1966.    * The XMLHttpRequest object that performs the connection.
  1967.    */
  1968.   _request  : null,
  1969.  
  1970.   /**
  1971.    * The nsIUpdateCheckListener callback
  1972.    */
  1973.   _callback : null,
  1974.  
  1975.   /**
  1976.    * The URL of the update service XML file to connect to that contains details
  1977.    * about available updates.
  1978.    */
  1979.   getUpdateURL: function UC_getUpdateURL(force) {
  1980.     this._forced = force;
  1981.  
  1982.     // Use the override URL if specified.
  1983.     var url = getPref("getCharPref", PREF_APP_UPDATE_URL_OVERRIDE, null);
  1984.  
  1985.     // Otherwise, construct the update URL from component parts.
  1986.     if (!url) {
  1987.       try {
  1988.         url = getDefaultPrefBranch().getCharPref(PREF_APP_UPDATE_URL);
  1989.       } catch (e) {
  1990.       }
  1991.     }
  1992.  
  1993.     if (!url || url == "") {
  1994.       LOG("Checker", "getUpdateURL - update URL not defined");
  1995.       return null;
  1996.     }
  1997.  
  1998.     url = url.replace(/%PRODUCT%/g, gApp.name);
  1999.     url = url.replace(/%VERSION%/g, gApp.version);
  2000.     url = url.replace(/%BUILD_ID%/g, gApp.appBuildID);
  2001.     url = url.replace(/%BUILD_TARGET%/g, gApp.OS + "_" + gABI);
  2002.     url = url.replace(/%OS_VERSION%/g, gOSVersion);
  2003.     if (/%LOCALE%/.test(url))
  2004.       url = url.replace(/%LOCALE%/g, getLocale());
  2005.     url = url.replace(/%CHANNEL%/g, getUpdateChannel());
  2006.     url = url.replace(/%PLATFORM_VERSION%/g, gApp.platformVersion);
  2007.     url = url.replace(/%DISTRIBUTION%/g,
  2008.                       getDistributionPrefValue(PREF_APP_DISTRIBUTION));
  2009.     url = url.replace(/%DISTRIBUTION_VERSION%/g,
  2010.                       getDistributionPrefValue(PREF_APP_DISTRIBUTION_VERSION));
  2011.     url = url.replace(/\+/g, "%2B");
  2012.  
  2013.     if (force)
  2014.       url += (url.indexOf("?") != -1 ? "&" : "?") + "force=1";
  2015.  
  2016.     LOG("Checker", "getUpdateURL - update URL: " + url);
  2017.     return url;
  2018.   },
  2019.  
  2020.   /**
  2021.    * See nsIUpdateService.idl
  2022.    */
  2023.   checkForUpdates: function UC_checkForUpdates(listener, force) {
  2024.     if (!listener)
  2025.       throw Cr.NS_ERROR_NULL_POINTER;
  2026.  
  2027.     var url = this.getUpdateURL(force);
  2028.     if (!url || (!this.enabled && !force))
  2029.       return;
  2030.  
  2031.     this._request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].
  2032.                     createInstance(Ci.nsIXMLHttpRequest);
  2033.     this._request.open("GET", url, true);
  2034.     this._request.channel.notificationCallbacks = new BadCertHandler();
  2035.     this._request.overrideMimeType("text/xml");
  2036.     this._request.setRequestHeader("Cache-Control", "no-cache");
  2037.  
  2038.     var self = this;
  2039.     this._request.onerror     = function(event) { self.onError(event);    };
  2040.     this._request.onload      = function(event) { self.onLoad(event);     };
  2041.     this._request.onprogress  = function(event) { self.onProgress(event); };
  2042.  
  2043.     LOG("Checker", "checkForUpdates - sending request to: " + url);
  2044.     this._request.send(null);
  2045.  
  2046.     this._callback = listener;
  2047.   },
  2048.  
  2049.   /**
  2050.    * When progress associated with the XMLHttpRequest is received.
  2051.    * @param   event
  2052.    *          The nsIDOMLSProgressEvent for the load.
  2053.    */
  2054.   onProgress: function UC_onProgress(event) {
  2055.     LOG("Checker", "onProgress - " + event.position + "/" + event.totalSize);
  2056.     this._callback.onProgress(event.target, event.position, event.totalSize);
  2057.   },
  2058.  
  2059.   /**
  2060.    * Returns an array of nsIUpdate objects discovered by the update check.
  2061.    */
  2062.   get _updates() {
  2063.     var updatesElement = this._request.responseXML.documentElement;
  2064.     if (!updatesElement) {
  2065.       LOG("Checker", "get_updates - empty updates document?!");
  2066.       return [];
  2067.     }
  2068.  
  2069.     if (updatesElement.nodeName != "updates") {
  2070.       LOG("Checker", "get_updates - unexpected node name!");
  2071.       throw "";
  2072.     }
  2073.  
  2074.     const ELEMENT_NODE = Ci.nsIDOMNode.ELEMENT_NODE;
  2075.     var updates = [];
  2076.     for (var i = 0; i < updatesElement.childNodes.length; ++i) {
  2077.       var updateElement = updatesElement.childNodes.item(i);
  2078.       if (updateElement.nodeType != ELEMENT_NODE ||
  2079.           updateElement.localName != "update")
  2080.         continue;
  2081.  
  2082.       updateElement.QueryInterface(Ci.nsIDOMElement);
  2083.       try {
  2084.         var update = new Update(updateElement);
  2085.       } catch (e) {
  2086.         LOG("Checker", "get_updates - invalid <update/>, ignoring...");
  2087.         continue;
  2088.       }
  2089.       update.serviceURL = this.getUpdateURL(this._forced);
  2090.       update.channel = getUpdateChannel();
  2091.       updates.push(update);
  2092.     }
  2093.  
  2094.     return updates;
  2095.   },
  2096.  
  2097.   /**
  2098.    * Returns the status code for the XMLHttpRequest
  2099.    */
  2100.   _getChannelStatus: function UC__getChannelStatus(request) {
  2101.     var status = 0;
  2102.     try {
  2103.       status = request.status;
  2104.     }
  2105.     catch (e) {
  2106.     }
  2107.  
  2108.     if (status == 0)
  2109.       status = request.channel.QueryInterface(Ci.nsIRequest).status;
  2110.     return status;
  2111.   },
  2112.  
  2113.   /**
  2114.    * The XMLHttpRequest succeeded and the document was loaded.
  2115.    * @param   event
  2116.    *          The nsIDOMEvent for the load
  2117.    */
  2118.   onLoad: function UC_onLoad(event) {
  2119.     LOG("Checker", "onLoad - request completed downloading document");
  2120.  
  2121.     try {
  2122.       checkCert(this._request.channel);
  2123.       // Analyze the resulting DOM and determine the set of updates to install
  2124.       var updates = this._updates;
  2125.  
  2126.       LOG("Checker", "onLoad - number of updates available: " + updates.length);
  2127.  
  2128.       // ... and tell the Update Service about what we discovered.
  2129.       this._callback.onCheckComplete(event.target, updates, updates.length);
  2130.     }
  2131.     catch (e) {
  2132.       LOG("Checker", "onLoad - there was a problem with the update service " +
  2133.           "URL specified, either the XML file was malformed or it does not " +
  2134.           "exist at the location specified. Exception: " + e);
  2135.       var request = event.target;
  2136.       var status = this._getChannelStatus(request);
  2137.       LOG("Checker", "onLoad - request.status: " + status);
  2138.       var update = new Update(null);
  2139.       update.statusText = getStatusTextFromCode(status, 404);
  2140.       this._callback.onError(request, update);
  2141.     }
  2142.  
  2143.     this._request = null;
  2144.   },
  2145.  
  2146.   /**
  2147.    * There was an error of some kind during the XMLHttpRequest
  2148.    * @param   event
  2149.    *          The nsIDOMEvent for the load
  2150.    */
  2151.   onError: function UC_onError(event) {
  2152.     var request = event.target;
  2153.     var status = this._getChannelStatus(request);
  2154.     LOG("Checker", "onError - request.status: " + status);
  2155.  
  2156.     // If we can't find an error string specific to this status code,
  2157.     // just use the 200 message from above, which means everything
  2158.     // "looks" fine but there was probably an XML error or a bogus file.
  2159.     var update = new Update(null);
  2160.     update.statusText = getStatusTextFromCode(status, 200);
  2161.     this._callback.onError(request, update);
  2162.  
  2163.     this._request = null;
  2164.   },
  2165.  
  2166.   /**
  2167.    * Whether or not we are allowed to do update checking.
  2168.    */
  2169.   _enabled: true,
  2170.   get enabled() {
  2171.     var aus = Cc["@mozilla.org/updates/update-service;1"].
  2172.               getService(Ci.nsIApplicationUpdateService);
  2173.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true) &&
  2174.                   aus.canUpdate && this._enabled;
  2175.     return enabled;
  2176.   },
  2177.  
  2178.   /**
  2179.    * See nsIUpdateService.idl
  2180.    */
  2181.   stopChecking: function UC_stopChecking(duration) {
  2182.     // Always stop the current check
  2183.     if (this._request)
  2184.       this._request.abort();
  2185.  
  2186.     switch (duration) {
  2187.     case Ci.nsIUpdateChecker.CURRENT_SESSION:
  2188.       this._enabled = false;
  2189.       break;
  2190.     case Ci.nsIUpdateChecker.ANY_CHECKS:
  2191.       this._enabled = false;
  2192.       gPref.setBoolPref(PREF_APP_UPDATE_ENABLED, this._enabled);
  2193.       break;
  2194.     }
  2195.   },
  2196.  
  2197.   classDescription: "Update Checker",
  2198.   contractID: "@mozilla.org/updates/update-checker;1",
  2199.   classID: Components.ID("{898CDC9B-E43F-422F-9CC4-2F6291B415A3}"),
  2200.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdateChecker])
  2201. };
  2202.  
  2203. /**
  2204.  * Manages the download of updates
  2205.  * @param   background
  2206.  *          Whether or not this downloader is operating in background
  2207.  *          update mode.
  2208.  * @constructor
  2209.  */
  2210. function Downloader(background) {
  2211.   this.background = background;
  2212. }
  2213. Downloader.prototype = {
  2214.   /**
  2215.    * The nsIUpdatePatch that we are downloading
  2216.    */
  2217.   _patch: null,
  2218.  
  2219.   /**
  2220.    * The nsIUpdate that we are downloading
  2221.    */
  2222.   _update: null,
  2223.  
  2224.   /**
  2225.    * The nsIIncrementalDownload object handling the download
  2226.    */
  2227.   _request: null,
  2228.  
  2229.   /**
  2230.    * Whether or not the update being downloaded is a complete replacement of
  2231.    * the user's existing installation or a patch representing the difference
  2232.    * between the new version and the previous version.
  2233.    */
  2234.   isCompleteUpdate: null,
  2235.  
  2236.   /**
  2237.    * Cancels the active download.
  2238.    */
  2239.   cancel: function Downloader_cancel() {
  2240.     if (this._request && this._request instanceof Ci.nsIRequest) {
  2241.       const NS_BINDING_ABORTED = 0x804b0002;
  2242.       this._request.cancel(NS_BINDING_ABORTED);
  2243.     }
  2244.   },
  2245.  
  2246.   /**
  2247.    * Whether or not a patch has been downloaded and staged for installation.
  2248.    */
  2249.   get patchIsStaged() {
  2250.     return readStatusFile(getUpdatesDir()) == STATE_PENDING;
  2251.   },
  2252.  
  2253.   /**
  2254.    * Verify the downloaded file.  We assume that the download is complete at
  2255.    * this point.
  2256.    */
  2257.   _verifyDownload: function Downloader__verifyDownload() {
  2258.     if (!this._request)
  2259.       return false;
  2260.  
  2261.     var destination = this._request.destination;
  2262.  
  2263.     // Ensure that the file size matches the expected file size.
  2264.     if (destination.fileSize != this._patch.size)
  2265.       return false;
  2266.  
  2267.     var fileStream = Cc["@mozilla.org/network/file-input-stream;1"].
  2268.                      createInstance(Ci.nsIFileInputStream);
  2269.     fileStream.init(destination, MODE_RDONLY, PERMS_FILE, 0);
  2270.  
  2271.     try {
  2272.       var hash = Cc["@mozilla.org/security/hash;1"].
  2273.                  createInstance(Ci.nsICryptoHash);
  2274.       var hashFunction = Ci.nsICryptoHash[this._patch.hashFunction.toUpperCase()];
  2275.       if (hashFunction == undefined)
  2276.         throw Cr.NS_ERROR_UNEXPECTED;
  2277.       hash.init(hashFunction);
  2278.       hash.updateFromStream(fileStream, -1);
  2279.       // NOTE: For now, we assume that the format of _patch.hashValue is hex
  2280.       // encoded binary (such as what is typically output by programs like
  2281.       // sha1sum).  In the future, this may change to base64 depending on how
  2282.       // we choose to compute these hashes.
  2283.       digest = binaryToHex(hash.finish(false));
  2284.     } catch (e) {
  2285.       LOG("Downloader", "_verifyDownload - failed to compute hash of " +
  2286.           "downloaded update archive");
  2287.       digest = "";
  2288.     }
  2289.  
  2290.     fileStream.close();
  2291.  
  2292.     return digest == this._patch.hashValue.toLowerCase();
  2293.   },
  2294.  
  2295.   /**
  2296.    * Select the patch to use given the current state of updateDir and the given
  2297.    * set of update patches.
  2298.    * @param   update
  2299.    *          A nsIUpdate object to select a patch from
  2300.    * @param   updateDir
  2301.    *          A nsIFile representing the update directory
  2302.    * @returns A nsIUpdatePatch object to download
  2303.    */
  2304.   _selectPatch: function Downloader__selectPatch(update, updateDir) {
  2305.     // Given an update to download, we will always try to download the patch
  2306.     // for a partial update over the patch for a full update.
  2307.  
  2308.     /**
  2309.      * Return the first UpdatePatch with the given type.
  2310.      * @param   type
  2311.      *          The type of the patch ("complete" or "partial")
  2312.      * @returns A nsIUpdatePatch object matching the type specified
  2313.      */
  2314.     function getPatchOfType(type) {
  2315.       for (var i = 0; i < update.patchCount; ++i) {
  2316.         var patch = update.getPatchAt(i);
  2317.         if (patch && patch.type == type)
  2318.           return patch;
  2319.       }
  2320.       return null;
  2321.     }
  2322.  
  2323.     // Look to see if any of the patches in the Update object has been
  2324.     // pre-selected for download, otherwise we must figure out which one
  2325.     // to select ourselves.
  2326.     var selectedPatch = update.selectedPatch;
  2327.  
  2328.     var state = readStatusFile(updateDir);
  2329.  
  2330.     // If this is a patch that we know about, then select it.  If it is a patch
  2331.     // that we do not know about, then remove it and use our default logic.
  2332.     var useComplete = false;
  2333.     if (selectedPatch) {
  2334.       LOG("Downloader", "_selectPatch - found existing patch with state: " + state);
  2335.       switch (state) {
  2336.       case STATE_DOWNLOADING:
  2337.         LOG("Downloader", "_selectPatch - resuming download");
  2338.         return selectedPatch;
  2339.       case STATE_PENDING:
  2340.         LOG("Downloader", "_selectPatch - already downloaded and staged");
  2341.         return null;
  2342.       default:
  2343.         // Something went wrong when we tried to apply the previous patch.
  2344.         // Try the complete patch next time.
  2345.         if (update && selectedPatch.type == "partial") {
  2346.           useComplete = true;
  2347.         } else {
  2348.           // This is a pretty fatal error.  Just bail.
  2349.           LOG("Downloader", "_selectPatch - failed to apply complete patch!");
  2350.           writeStatusFile(updateDir, STATE_NONE);
  2351.           writeVersionFile(getUpdatesDir(), null);
  2352.           return null;
  2353.         }
  2354.       }
  2355.  
  2356.       selectedPatch = null;
  2357.     }
  2358.  
  2359.     // If we were not able to discover an update from a previous download, we
  2360.     // select the best patch from the given set.
  2361.     var partialPatch = getPatchOfType("partial");
  2362.     if (!useComplete)
  2363.       selectedPatch = partialPatch;
  2364.     if (!selectedPatch) {
  2365.       if (partialPatch)
  2366.         partialPatch.selected = false;
  2367.       selectedPatch = getPatchOfType("complete");
  2368.     }
  2369.  
  2370.     // Restore the updateDir since we may have deleted it.
  2371.     updateDir = getUpdatesDir();
  2372.  
  2373.     // if update only contains a partial patch, selectedPatch == null here if
  2374.     // the partial patch has been attempted and fails and we're trying to get a
  2375.     // complete patch
  2376.     if (selectedPatch)
  2377.       selectedPatch.selected = true;
  2378.  
  2379.     update.isCompleteUpdate = useComplete;
  2380.  
  2381.     // Reset the Active Update object on the Update Manager and flush the
  2382.     // Active Update DB.
  2383.     var um = Cc["@mozilla.org/updates/update-manager;1"].
  2384.              getService(Ci.nsIUpdateManager);
  2385.     um.activeUpdate = update;
  2386.  
  2387.     return selectedPatch;
  2388.   },
  2389.  
  2390.   /**
  2391.    * Whether or not we are currently downloading something.
  2392.    */
  2393.   get isBusy() {
  2394.     return this._request != null;
  2395.   },
  2396.  
  2397.   /**
  2398.    * Download and stage the given update.
  2399.    * @param   update
  2400.    *          A nsIUpdate object to download a patch for. Cannot be null.
  2401.    */
  2402.   downloadUpdate: function Downloader_downloadUpdate(update) {
  2403.     if (!update)
  2404.       throw Cr.NS_ERROR_NULL_POINTER;
  2405.  
  2406.     var updateDir = getUpdatesDir();
  2407.  
  2408.     this._update = update;
  2409.  
  2410.     // This function may return null, which indicates that there are no patches
  2411.     // to download.
  2412.     this._patch = this._selectPatch(update, updateDir);
  2413.     if (!this._patch) {
  2414.       LOG("Downloader", "downloadUpdate - no patch to download");
  2415.       return readStatusFile(updateDir);
  2416.     }
  2417.     this.isCompleteUpdate = this._patch.type == "complete";
  2418.  
  2419.     var patchFile = updateDir.clone();
  2420.     patchFile.append(FILE_UPDATE_ARCHIVE);
  2421.  
  2422.     var ios = Cc["@mozilla.org/network/io-service;1"].
  2423.               getService(Ci.nsIIOService);
  2424.     var uri = ios.newURI(this._patch.URL, null, null);
  2425.  
  2426.     this._request = Cc["@mozilla.org/network/incremental-download;1"].
  2427.                     createInstance(Ci.nsIIncrementalDownload);
  2428.  
  2429.     LOG("Downloader", "downloadUpdate - downloading from " + uri.spec + " to " +
  2430.         patchFile.path);
  2431.  
  2432.     var interval = this.background ? DOWNLOAD_BACKGROUND_INTERVAL
  2433.                                    : DOWNLOAD_FOREGROUND_INTERVAL;
  2434.     this._request.init(uri, patchFile, DOWNLOAD_CHUNK_SIZE, interval);
  2435.     this._request.start(this, null);
  2436.  
  2437.     writeStatusFile(updateDir, STATE_DOWNLOADING);
  2438.     this._patch.QueryInterface(Ci.nsIWritablePropertyBag);
  2439.     this._patch.state = STATE_DOWNLOADING;
  2440.     var um = Cc["@mozilla.org/updates/update-manager;1"].
  2441.              getService(Ci.nsIUpdateManager);
  2442.     um.saveUpdates();
  2443.     return STATE_DOWNLOADING;
  2444.   },
  2445.  
  2446.   /**
  2447.    * An array of download listeners to notify when we receive
  2448.    * nsIRequestObserver or nsIProgressEventSink method calls.
  2449.    */
  2450.   _listeners: [],
  2451.  
  2452.   /**
  2453.    * Adds a listener to the download process
  2454.    * @param   listener
  2455.    *          A download listener, implementing nsIRequestObserver and
  2456.    *          nsIProgressEventSink
  2457.    */
  2458.   addDownloadListener: function Downloader_addDownloadListener(listener) {
  2459.     for (var i = 0; i < this._listeners.length; ++i) {
  2460.       if (this._listeners[i] == listener)
  2461.         return;
  2462.     }
  2463.     this._listeners.push(listener);
  2464.   },
  2465.  
  2466.   /**
  2467.    * Removes a download listener
  2468.    * @param   listener
  2469.    *          The listener to remove.
  2470.    */
  2471.   removeDownloadListener: function Downloader_removeDownloadListener(listener) {
  2472.     for (var i = 0; i < this._listeners.length; ++i) {
  2473.       if (this._listeners[i] == listener) {
  2474.         this._listeners.splice(i, 1);
  2475.         return;
  2476.       }
  2477.     }
  2478.   },
  2479.  
  2480.   /**
  2481.    * When the async request begins
  2482.    * @param   request
  2483.    *          The nsIRequest object for the transfer
  2484.    * @param   context
  2485.    *          Additional data
  2486.    */
  2487.   onStartRequest: function Downloader_onStartRequest(request, context) {
  2488.     if (request instanceof Ci.nsIIncrementalDownload)
  2489.       LOG("Downloader", "onStartRequest - spec: " + request.URI.spec);
  2490.  
  2491.     var listenerCount = this._listeners.length;
  2492.     for (var i = 0; i < listenerCount; ++i)
  2493.       this._listeners[i].onStartRequest(request, context);
  2494.   },
  2495.  
  2496.   /**
  2497.    * When new data has been downloaded
  2498.    * @param   request
  2499.    *          The nsIRequest object for the transfer
  2500.    * @param   context
  2501.    *          Additional data
  2502.    * @param   progress
  2503.    *          The current number of bytes transferred
  2504.    * @param   maxProgress
  2505.    *          The total number of bytes that must be transferred
  2506.    */
  2507.   onProgress: function Downloader_onProgress(request, context, progress,
  2508.                                              maxProgress) {
  2509.     LOG("Downloader.onProgress", "onProgress - progress: " + progress + "/" +
  2510.         maxProgress);
  2511.  
  2512.     var listenerCount = this._listeners.length;
  2513.     for (var i = 0; i < listenerCount; ++i) {
  2514.       var listener = this._listeners[i];
  2515.       if (listener instanceof Ci.nsIProgressEventSink)
  2516.         listener.onProgress(request, context, progress, maxProgress);
  2517.     }
  2518.   },
  2519.  
  2520.   /**
  2521.    * When we have new status text
  2522.    * @param   request
  2523.    *          The nsIRequest object for the transfer
  2524.    * @param   context
  2525.    *          Additional data
  2526.    * @param   status
  2527.    *          A status code
  2528.    * @param   statusText
  2529.    *          Human readable version of |status|
  2530.    */
  2531.   onStatus: function Downloader_onStatus(request, context, status, statusText) {
  2532.     LOG("Downloader", "onStatus - status: " + status + ", statusText: " +
  2533.         statusText);
  2534.  
  2535.     var listenerCount = this._listeners.length;
  2536.     for (var i = 0; i < listenerCount; ++i) {
  2537.       var listener = this._listeners[i];
  2538.       if (listener instanceof Ci.nsIProgressEventSink)
  2539.         listener.onStatus(request, context, status, statusText);
  2540.     }
  2541.   },
  2542.  
  2543.   /**
  2544.    * When data transfer ceases
  2545.    * @param   request
  2546.    *          The nsIRequest object for the transfer
  2547.    * @param   context
  2548.    *          Additional data
  2549.    * @param   status
  2550.    *          Status code containing the reason for the cessation.
  2551.    */
  2552.   onStopRequest: function  Downloader_onStopRequest(request, context, status) {
  2553.     if (request instanceof Ci.nsIIncrementalDownload)
  2554.       LOG("Downloader", "onStopRequest - spec: " + request.URI.spec +
  2555.           ", status: " + status);
  2556.  
  2557.     var state = this._patch.state;
  2558.     var shouldShowPrompt = false;
  2559.     var deleteActiveUpdate = false;
  2560.     const NS_BINDING_ABORTED = 0x804b0002;
  2561.     const NS_ERROR_ABORT = 0x80004004;
  2562.     if (Components.isSuccessCode(status)) {
  2563.       var sbs = Cc["@mozilla.org/intl/stringbundle;1"].
  2564.                 getService(Ci.nsIStringBundleService);
  2565.       var updateStrings = sbs.createBundle(URI_UPDATES_PROPERTIES);
  2566.       if (this._verifyDownload()) {
  2567.         state = STATE_PENDING;
  2568.  
  2569.         // We only need to explicitly show the prompt if this is a backround
  2570.         // download, since otherwise some kind of UI is already visible and
  2571.         // that UI will notify.
  2572.         if (this.background)
  2573.           shouldShowPrompt = true;
  2574.  
  2575.         // Tell the updater.exe we're ready to apply.
  2576.         writeStatusFile(getUpdatesDir(), state);
  2577.         writeVersionFile(getUpdatesDir(), this._update.extensionVersion);
  2578.         this._update.installDate = (new Date()).getTime();
  2579.         this._update.statusText = updateStrings.GetStringFromName("installPending");
  2580.       }
  2581.       else {
  2582.         LOG("Downloader", "onStopRequest - download verification failed");
  2583.         state = STATE_DOWNLOAD_FAILED;
  2584.  
  2585.         // TODO: use more informative error code here
  2586.         status = Cr.NS_ERROR_UNEXPECTED;
  2587.  
  2588.         // Yes, this code is a string.
  2589.         const vfCode = "verification_failed";
  2590.         var message = getStatusTextFromCode(vfCode, vfCode);
  2591.         this._update.statusText = message;
  2592.  
  2593.         if (this._update.isCompleteUpdate)
  2594.           deleteActiveUpdate = true;
  2595.  
  2596.         // Destroy the updates directory, since we're done with it.
  2597.         cleanUpUpdatesDir();
  2598.       }
  2599.     }
  2600.     else if (status != NS_BINDING_ABORTED &&
  2601.              status != NS_ERROR_ABORT) {
  2602.       LOG("Downloader", "onStopRequest - non-verification failure");
  2603.       // Some sort of other failure, log this in the |statusText| property
  2604.       state = STATE_DOWNLOAD_FAILED;
  2605.  
  2606.       // XXXben - if |request| (The Incremental Download) provided a means
  2607.       // for accessing the http channel we could do more here.
  2608.  
  2609.       const NS_BINDING_FAILED = 2152398849;
  2610.       this._update.statusText = getStatusTextFromCode(status,
  2611.         NS_BINDING_FAILED);
  2612.  
  2613.       // Destroy the updates directory, since we're done with it.
  2614.       cleanUpUpdatesDir();
  2615.  
  2616.       deleteActiveUpdate = true;
  2617.     }
  2618.     LOG("Downloader", "onStopRequest - setting state to: " + state);
  2619.     this._patch.state = state;
  2620.     var um = Cc["@mozilla.org/updates/update-manager;1"].
  2621.              getService(Ci.nsIUpdateManager);
  2622.     if (deleteActiveUpdate) {
  2623.       this._update.installDate = (new Date()).getTime();
  2624.       um.activeUpdate = null;
  2625.     }
  2626.     else {
  2627.       if (um.activeUpdate)
  2628.         um.activeUpdate.state = state;
  2629.     }
  2630.     um.saveUpdates();
  2631.  
  2632.     var listenerCount = this._listeners.length;
  2633.     for (var i = 0; i < listenerCount; ++i)
  2634.       this._listeners[i].onStopRequest(request, context, status);
  2635.  
  2636.     this._request = null;
  2637.  
  2638.     if (state == STATE_DOWNLOAD_FAILED) {
  2639.       if (!this._update.isCompleteUpdate) {
  2640.         var allFailed = true;
  2641.  
  2642.         // If we were downloading a patch and the patch verification phase
  2643.         // failed, log this and then commence downloading the complete update.
  2644.         LOG("Downloader", "onStopRequest - verification of patch failed, " +
  2645.             "downloading complete update");
  2646.         this._update.isCompleteUpdate = true;
  2647.         var status = this.downloadUpdate(this._update);
  2648.  
  2649.         if (status == STATE_NONE) {
  2650.           cleanupActiveUpdate();
  2651.         } else {
  2652.           allFailed = false;
  2653.         }
  2654.         // This will reset the |.state| property on this._update if a new
  2655.         // download initiates.
  2656.       }
  2657.  
  2658.       // if we still fail after trying a complete download, give up completely
  2659.       if (allFailed) {
  2660.         // In all other failure cases, i.e. we're S.O.L. - no more failing over
  2661.         // ...
  2662.  
  2663.         // If this was ever a foreground download, and now there is no UI active
  2664.         // (e.g. because the user closed the download window) and there was an
  2665.         // error, we must notify now. Otherwise we can keep the failure to
  2666.         // ourselves since the user won't be expecting it.
  2667.         try {
  2668.           this._update.QueryInterface(Ci.nsIWritablePropertyBag);
  2669.           var fgdl = this._update.getProperty("foregroundDownload");
  2670.         }
  2671.         catch (e) {
  2672.         }
  2673.  
  2674.         if (fgdl == "true") {
  2675.           var prompter = Cc["@mozilla.org/updates/update-prompt;1"].
  2676.                          createInstance(Ci.nsIUpdatePrompt);
  2677.           this._update.QueryInterface(Ci.nsIWritablePropertyBag);
  2678.           this._update.setProperty("downloadFailed", "true");
  2679.           prompter.showUpdateError(this._update);
  2680.         }
  2681.       }
  2682.  
  2683.       // Prevent leaking the update object (bug 454964)
  2684.       this._update = null;
  2685.       // the complete download succeeded or total failure was handled, so exit
  2686.       return;
  2687.     }
  2688.  
  2689.     // Do this after *everything* else, since it will likely cause the app
  2690.     // to shut down.
  2691.     if (shouldShowPrompt) {
  2692.       // Notify the user that an update has been downloaded and is ready for
  2693.       // installation (i.e. that they should restart the application). We do
  2694.       // not notify on failed update attempts.
  2695.       var prompter = Cc["@mozilla.org/updates/update-prompt;1"].
  2696.                      createInstance(Ci.nsIUpdatePrompt);
  2697.       prompter.showUpdateDownloaded(this._update, true);
  2698.     }
  2699.     // Prevent leaking the update object (bug 454964)
  2700.     this._update = null;
  2701.   },
  2702.  
  2703.   /**
  2704.    * See nsIInterfaceRequestor.idl
  2705.    */
  2706.   getInterface: function Downloader_getInterface(iid) {
  2707.     // The network request may require proxy authentication, so provide the
  2708.     // default nsIAuthPrompt if requested.
  2709.     if (iid.equals(Ci.nsIAuthPrompt)) {
  2710.       var prompt = Cc["@mozilla.org/network/default-auth-prompt;1"].
  2711.                    createInstance();
  2712.       return prompt.QueryInterface(iid);
  2713.     }
  2714.     throw Components.results.NS_NOINTERFACE;
  2715.   },
  2716.  
  2717.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIRequestObserver,
  2718.                                          Ci.nsIProgressEventSink,
  2719.                                          Ci.nsIInterfaceRequestor])
  2720. };
  2721.  
  2722. /**
  2723.  * A manager for update check timers. Manages timers that fire over long
  2724.  * periods of time (e.g. days, weeks).
  2725.  * @constructor
  2726.  */
  2727. function TimerManager() {
  2728.   getObserverService().addObserver(this, "xpcom-shutdown", false);
  2729.  
  2730.   this._timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  2731.   var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2732.   this._timer.initWithCallback(this, timerInterval,
  2733.                                Ci.nsITimer.TYPE_REPEATING_SLACK);
  2734. }
  2735. TimerManager.prototype = {
  2736.   /**
  2737.    * See nsIObserver.idl
  2738.    */
  2739.   observe: function TM_observe(subject, topic, data) {
  2740.     if (topic == "xpcom-shutdown") {
  2741.      getObserverService().removeObserver(this, "xpcom-shutdown");
  2742.  
  2743.       // Release everything we hold onto.
  2744.       for (var timerID in this._timers)
  2745.         delete this._timers[timerID];
  2746.       this._timer = null;
  2747.       this._timers = null;
  2748.     }
  2749.   },
  2750.  
  2751.   /**
  2752.    * The Checker Timer
  2753.    */
  2754.   _timer: null,
  2755.  
  2756.   /**
  2757.    * The set of registered timers.
  2758.    */
  2759.   _timers: { },
  2760.  
  2761.   /**
  2762.    * Called when the checking timer fires.
  2763.    * @param   timer
  2764.    *          The checking timer that fired.
  2765.    */
  2766.   notify: function TM_notify(timer) {
  2767.     for (var timerID in this._timers) {
  2768.       var timerData = this._timers[timerID];
  2769.       var lastUpdateTime = timerData.lastUpdateTime;
  2770.       var now = Math.round(Date.now() / 1000);
  2771.  
  2772.       // Fudge the lastUpdateTime by some random increment of the update
  2773.       // check interval (e.g. some random slice of 10 minutes) so that when
  2774.       // the time comes to check, we offset each client request by a random
  2775.       // amount so they don't all hit at once. app.update.timer is in milliseconds,
  2776.       // whereas app.update.lastUpdateTime is in seconds
  2777.       var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2778.       lastUpdateTime += Math.round(Math.random() * timerInterval / 1000);
  2779.  
  2780.       if ((now - lastUpdateTime) > timerData.interval &&
  2781.           timerData.callback instanceof Ci.nsITimerCallback) {
  2782.         timerData.callback.notify(timer);
  2783.         timerData.lastUpdateTime = now;
  2784.         var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, timerID);
  2785.         gPref.setIntPref(preference, now);
  2786.       }
  2787.     }
  2788.   },
  2789.  
  2790.   /**
  2791.    * See nsIUpdateService.idl
  2792.    */
  2793.   registerTimer: function TM_registerTimer(id, callback, interval) {
  2794.     var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, id);
  2795.     var now = Math.round(Date.now() / 1000);
  2796.     var lastUpdateTime = null;
  2797.     if (gPref.prefHasUserValue(preference)) {
  2798.       lastUpdateTime = gPref.getIntPref(preference);
  2799.     } else {
  2800.       gPref.setIntPref(preference, now);
  2801.       lastUpdateTime = now;
  2802.     }
  2803.     this._timers[id] = { callback       : callback,
  2804.                          interval       : interval,
  2805.                          lastUpdateTime : lastUpdateTime };
  2806.   },
  2807.  
  2808.   classDescription: "Timer Manager",
  2809.   contractID: "@mozilla.org/updates/timer-manager;1",
  2810.   classID: Components.ID("{B322A5C0-A419-484E-96BA-D7182163899F}"),
  2811.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdateTimerManager,
  2812.                                          Ci.nsITimerCallback,
  2813.                                          Ci.nsIObserver])
  2814. };
  2815.  
  2816. /**
  2817.  * UpdatePrompt
  2818.  * An object which can prompt the user with information about updates, request
  2819.  * action, etc. Embedding clients can override this component with one that
  2820.  * invokes a native front end.
  2821.  * @constructor
  2822.  */
  2823. function UpdatePrompt() {
  2824. }
  2825. UpdatePrompt.prototype = {
  2826.   /**
  2827.    * See nsIUpdateService.idl
  2828.    */
  2829.   checkForUpdates: function UP_checkForUpdates() {
  2830.     this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, UPDATE_WINDOW_NAME,
  2831.                  null, null);
  2832.   },
  2833.  
  2834.   /**
  2835.    * See nsIUpdateService.idl
  2836.    */
  2837.   showUpdateAvailable: function UP_showUpdateAvailable(update) {
  2838.     if (!this._enabled || this._getUpdateWindow())
  2839.       return;
  2840.  
  2841.     var bundle = this._updateBundle;
  2842.     var stringsPrefix = "updateAvailable_" + update.type + ".";
  2843.     var title = bundle.formatStringFromName(stringsPrefix + "title",
  2844.                                             [update.name], 1);
  2845.     var text = bundle.GetStringFromName(stringsPrefix + "text");
  2846.     var imageUrl = "";
  2847.     this._showUnobtrusiveUI(null, URI_UPDATE_PROMPT_DIALOG, null,
  2848.                            UPDATE_WINDOW_NAME, "updatesavailable", update,
  2849.                            title, text, imageUrl);
  2850.   },
  2851.  
  2852.   /**
  2853.    * See nsIUpdateService.idl
  2854.    */
  2855.   showUpdateDownloaded: function UP_showUpdateDownloaded(update, background) {
  2856.     if (background) {
  2857.       if (!this._enabled)
  2858.         return;
  2859.  
  2860.       var bundle = this._updateBundle;
  2861.       var stringsPrefix = "updateDownloaded_" + update.type + ".";
  2862.       var title = bundle.formatStringFromName(stringsPrefix + "title",
  2863.                                               [update.name], 1);
  2864.       var text = bundle.GetStringFromName(stringsPrefix + "text");
  2865.       var imageUrl = "";
  2866.       this._showUnobtrusiveUI(null, URI_UPDATE_PROMPT_DIALOG, null,
  2867.                               UPDATE_WINDOW_NAME, "finishedBackground", update,
  2868.                               title, text, imageUrl);
  2869.     } else {
  2870.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null,
  2871.                    UPDATE_WINDOW_NAME, "finishedBackground", update);
  2872.     }
  2873.   },
  2874.  
  2875.   /**
  2876.    * See nsIUpdateService.idl
  2877.    */
  2878.   showUpdateInstalled: function UP_showUpdateInstalled() {
  2879.     if (!this._enabled || this._getUpdateWindow() ||
  2880.         !getPref("getBoolPref", PREF_APP_UPDATE_SHOW_INSTALLED_UI, true))
  2881.       return;
  2882.  
  2883.     var page = "installed";
  2884.     var win = this._getUpdateWindow();
  2885.     if (win) {
  2886.       if (page && "setCurrentPage" in win)
  2887.         win.setCurrentPage(page);
  2888.       win.focus();
  2889.     }
  2890.     else {
  2891.       var openFeatures = "chrome,centerscreen,dialog=no,resizable=no,titlebar,toolbar=no";
  2892.       var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  2893.              getService(Ci.nsIWindowWatcher);
  2894.       var arg = Cc["@mozilla.org/supports-string;1"].
  2895.                 createInstance(Ci.nsISupportsString);
  2896.       arg.data = page;
  2897.       ww.openWindow(null, URI_UPDATE_PROMPT_DIALOG, null, openFeatures, arg);
  2898.     }
  2899.   },
  2900.  
  2901.   /**
  2902.    * See nsIUpdateService.idl
  2903.    */
  2904.   showUpdateError: function UP_showUpdateError(update) {
  2905.     if (!this._enabled)
  2906.       return;
  2907.  
  2908.     // In some cases, we want to just show a simple alert dialog:
  2909.     if (update.state == STATE_FAILED && update.errorCode == WRITE_ERROR) {
  2910.       var updateBundle = this._updateBundle;
  2911.       var title = updateBundle.GetStringFromName("updaterIOErrorTitle");
  2912.       var text = updateBundle.formatStringFromName("updaterIOErrorMsg",
  2913.                                                    [gApp.name, gApp.name], 2);
  2914.       var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  2915.                getService(Ci.nsIWindowWatcher);
  2916.       ww.getNewPrompter(null).alert(title, text);
  2917.     } else {
  2918.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, UPDATE_WINDOW_NAME,
  2919.                    "errors", update);
  2920.     }
  2921.   },
  2922.  
  2923.   /**
  2924.    * See nsIUpdateService.idl
  2925.    */
  2926.   showUpdateHistory: function UP_showUpdateHistory(parent) {
  2927.     this._showUI(parent, URI_UPDATE_HISTORY_DIALOG, "modal,dialog=yes",
  2928.                  "Update:History", null, null);
  2929.   },
  2930.  
  2931.   /**
  2932.    * Whether or not we are enabled (i.e. not in Silent mode)
  2933.    */
  2934.   get _enabled() {
  2935.     return !getPref("getBoolPref", PREF_APP_UPDATE_SILENT, false);
  2936.   },
  2937.  
  2938.   get _updateBundle() {
  2939.     return Cc["@mozilla.org/intl/stringbundle;1"].
  2940.            getService(Ci.nsIStringBundleService).
  2941.            createBundle(URI_UPDATES_PROPERTIES);
  2942.   },
  2943.  
  2944.   /**
  2945.    * Returns the update window if present.
  2946.    */
  2947.   _getUpdateWindow: function UP__getUpdateWindow() {
  2948.     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
  2949.              getService(Ci.nsIWindowMediator);
  2950.     return wm.getMostRecentWindow(UPDATE_WINDOW_NAME);
  2951.   },
  2952.  
  2953.   /**
  2954.    * Initiate a less obtrusive UI, starting with a non-modal notification alert
  2955.    * @param   parent
  2956.    *          A parent window, can be null
  2957.    * @param   uri
  2958.    *          The URI string of the dialog to show
  2959.    * @param   name
  2960.    *          The Window Name of the dialog to show, in case it is already open
  2961.    *          and can merely be focused
  2962.    * @param   page
  2963.    *          The page of the wizard to be displayed, if one is already open.
  2964.    * @param   update
  2965.    *          An update to pass to the UI in the window arguments.
  2966.    *          Can be null
  2967.    * @param   title
  2968.    *          The title for the notification alert.
  2969.    * @param   text
  2970.    *          The contents of the notification alert.
  2971.    * @param   imageUrl
  2972.    *          A URL identifying the image to put in the notification alert.
  2973.    */
  2974.   _showUnobtrusiveUI: function UP__showUnobUI(parent, uri, features, name, page,
  2975.                                               update, title, text, imageUrl) {
  2976.     var observer = {
  2977.       updatePrompt: this,
  2978.       service: null,
  2979.       timer: null,
  2980.       notify: function () {
  2981.         // the user hasn't restarted yet => prompt when idle
  2982.         this.service.removeObserver(this, "quit-application");
  2983.         // If the update window is already open skip showing the UI
  2984.         if (this.updatePrompt._getUpdateWindow())
  2985.           return;
  2986.         this.updatePrompt._showUIWhenIdle(parent, uri, features, name, page, update);
  2987.       },
  2988.       observe: function (aSubject, aTopic, aData) {
  2989.         switch (aTopic) {
  2990.           case "alertclickcallback":
  2991.             this.updatePrompt._showUI(parent, uri, features, name, page, update);
  2992.             // fall thru
  2993.           case "quit-application":
  2994.             this.timer.cancel();
  2995.             this.service.removeObserver(this, "quit-application");
  2996.             break;
  2997.         }
  2998.       }
  2999.     };
  3000.  
  3001.     try {
  3002.       var notifier = Cc["@mozilla.org/alerts-service;1"].
  3003.                      getService(Ci.nsIAlertsService);
  3004.       notifier.showAlertNotification(imageUrl, title, text, true, "", observer);
  3005.     }
  3006.     catch (e) {
  3007.       // Failed to retrieve alerts service, platform unsupported
  3008.       this._showUIWhenIdle(parent, uri, features, name, page, update);
  3009.       return;
  3010.     }
  3011.  
  3012.     observer.service = Cc["@mozilla.org/observer-service;1"].
  3013.                        getService(Ci.nsIObserverService);
  3014.     observer.service.addObserver(observer, "quit-application", false);
  3015.  
  3016.     // Give the user x seconds to react before showing the big UI
  3017.     var promptWaitTime = getPref("getIntPref", PREF_APP_UPDATE_PROMPTWAITTIME, 43200);
  3018.     observer.timer = Cc["@mozilla.org/timer;1"].
  3019.                      createInstance(Ci.nsITimer);
  3020.     observer.timer.initWithCallback(observer, promptWaitTime * 1000,
  3021.                                     observer.timer.TYPE_ONE_SHOT);
  3022.   },
  3023.  
  3024.   /**
  3025.    * Show the UI when the user was idle
  3026.    * @param   parent
  3027.    *          A parent window, can be null
  3028.    * @param   uri
  3029.    *          The URI string of the dialog to show
  3030.    * @param   name
  3031.    *          The Window Name of the dialog to show, in case it is already open
  3032.    *          and can merely be focused
  3033.    * @param   page
  3034.    *          The page of the wizard to be displayed, if one is already open.
  3035.    * @param   update
  3036.    *          An update to pass to the UI in the window arguments.
  3037.    *          Can be null
  3038.    */
  3039.   _showUIWhenIdle: function UP__showUIWhenIdle(parent, uri, features, name,
  3040.                                                page, update) {
  3041.     var idleService = Cc["@mozilla.org/widget/idleservice;1"].
  3042.                       getService(Ci.nsIIdleService);
  3043.  
  3044.     const IDLE_TIME = getPref("getIntPref", PREF_APP_UPDATE_IDLETIME, 60);
  3045.     if (idleService.idleTime / 1000 >= IDLE_TIME) {
  3046.       this._showUI(parent, uri, features, name, page, update);
  3047.     } else {
  3048.       var observerService = Cc["@mozilla.org/observer-service;1"].
  3049.                             getService(Ci.nsIObserverService);
  3050.       var observer = {
  3051.         updatePrompt: this,
  3052.         observe: function (aSubject, aTopic, aData) {
  3053.           switch (aTopic) {
  3054.             case "idle":
  3055.               // If the update window is already open skip showing the UI
  3056.               if (!this.updatePrompt._getUpdateWindow())
  3057.                 this.updatePrompt._showUI(parent, uri, features, name, page, update);
  3058.               // fall thru
  3059.             case "quit-application":
  3060.               idleService.removeIdleObserver(this, IDLE_TIME);
  3061.               observerService.removeObserver(this, "quit-application");
  3062.               break;
  3063.           }
  3064.         }
  3065.       };
  3066.       idleService.addIdleObserver(observer, IDLE_TIME);
  3067.       observerService.addObserver(observer, "quit-application", false);
  3068.     }
  3069.   },
  3070.  
  3071.   /**
  3072.    * Show the Update Checking UI
  3073.    * @param   parent
  3074.    *          A parent window, can be null
  3075.    * @param   uri
  3076.    *          The URI string of the dialog to show
  3077.    * @param   name
  3078.    *          The Window Name of the dialog to show, in case it is already open
  3079.    *          and can merely be focused
  3080.    * @param   page
  3081.    *          The page of the wizard to be displayed, if one is already open.
  3082.    * @param   update
  3083.    *          An update to pass to the UI in the window arguments.
  3084.    *          Can be null
  3085.    */
  3086.   _showUI: function UP__showUI(parent, uri, features, name, page, update) {
  3087.     var ary = null;
  3088.     if (update) {
  3089.       ary = Cc["@mozilla.org/supports-array;1"].
  3090.             createInstance(Ci.nsISupportsArray);
  3091.       ary.AppendElement(update);
  3092.     }
  3093.  
  3094.     var win = this._getUpdateWindow();
  3095.     if (win) {
  3096.       if (page && "setCurrentPage" in win)
  3097.         win.setCurrentPage(page);
  3098.       win.focus();
  3099.     }
  3100.     else {
  3101.       var openFeatures = "chrome,centerscreen,dialog=no,resizable=no,titlebar,toolbar=no";
  3102.       if (features)
  3103.         openFeatures += "," + features;
  3104.       var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  3105.                getService(Ci.nsIWindowWatcher);
  3106.       ww.openWindow(parent, uri, "", openFeatures, ary);
  3107.     }
  3108.   },
  3109.  
  3110.   classDescription: "Update Prompt",
  3111.   contractID: "@mozilla.org/updates/update-prompt;1",
  3112.   classID: Components.ID("{27ABA825-35B5-4018-9FDD-F99250A0E722}"),
  3113.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdatePrompt])
  3114. };
  3115.  
  3116. function NSGetModule(compMgr, fileSpec)
  3117.   XPCOMUtils.generateModule([UpdateService, Checker, UpdatePrompt, TimerManager, UpdateManager]);
  3118.  
  3119.